Search in sources :

Example 1 with AccessToken

use of com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken in project aws-sdk-android by aws-amplify.

the class AWSMobileClientPersistenceWithRestartabilityTest method signInAndVerifySignIn.

private void signInAndVerifySignIn() {
    try {
        final CountDownLatch stateNotificationLatch = new CountDownLatch(1);
        final AtomicReference<UserStateDetails> userState = new AtomicReference<UserStateDetails>();
        listener = new UserStateListener() {

            @Override
            public void onUserStateChanged(UserStateDetails details) {
                userState.set(details);
                auth.removeUserStateListener(listener);
                stateNotificationLatch.countDown();
            }
        };
        auth.addUserStateListener(listener);
        final SignInResult signInResult = auth.signIn(username, PASSWORD, null);
        assertEquals("Cannot support MFA in tests", SignInState.DONE, signInResult.getSignInState());
        assertTrue("isSignedIn is true", auth.isSignedIn());
        assertEquals(username, auth.getUsername());
        // Check credentials are available
        final AWSCredentials credentials = auth.getCredentials();
        assertNotNull("Credentials are null", credentials);
        assertNotNull("Access key is null", credentials.getAWSAccessKeyId());
        assertNotNull("Secret key is null", credentials.getAWSSecretKey());
        Tokens tokens = auth.getTokens();
        assertNotNull(tokens);
        Token accessToken = tokens.getAccessToken();
        assertNotNull(accessToken);
        assertTrue("Access token should not be expired", accessToken.getExpiration().after(new Date()));
        Token idToken = tokens.getIdToken();
        assertNotNull(idToken);
        assertTrue("Id token should not be expired", idToken.getExpiration().after(new Date()));
        Token refreshToken = tokens.getRefreshToken();
        assertNotNull(refreshToken);
        // Check one attribute
        final Map<String, String> userAttributes = auth.getUserAttributes();
        assertEquals(getPackageConfigure().getString("email"), userAttributes.get("email"));
        stateNotificationLatch.await(5, TimeUnit.SECONDS);
        UserStateDetails userStateDetails = userState.get();
        assertEquals(userStateDetails.getUserState(), UserState.SIGNED_IN);
        Map<String, String> details = userStateDetails.getDetails();
        assertNotEquals(getPackageConfigure().getString("identity_id"), details.toString());
    } catch (Exception ex) {
        fail(ex.getMessage());
    }
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) IdToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.IdToken) RefreshToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.RefreshToken) AccessToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken) Token(com.amazonaws.mobile.client.results.Token) CountDownLatch(java.util.concurrent.CountDownLatch) AWSCredentials(com.amazonaws.auth.AWSCredentials) Date(java.util.Date) JSONException(org.json.JSONException) UserNotConfirmedException(com.amazonaws.services.cognitoidentityprovider.model.UserNotConfirmedException) SignInResult(com.amazonaws.mobile.client.results.SignInResult) Tokens(com.amazonaws.mobile.client.results.Tokens)

Example 2 with AccessToken

use of com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken in project aws-sdk-android by aws-amplify.

the class LocalDataManager method getCachedSession.

/**
 * Returns cached tokens for a user as a {@link AuthUserSession}.
 * @param context Required: The host application {@link Context}.
 * @param clientId Required: Cognito App/Client Id.
 * @param username Required: The username.
 * @return {@link AuthUserSession}.
 */
public static AuthUserSession getCachedSession(final Context context, final String clientId, final String username, final Set<String> scopes) {
    AuthUserSession session = new AuthUserSession(null, null, null);
    if (username != null) {
        if (context == null || clientId == null || clientId.isEmpty()) {
            throw new InvalidParameterException("Application context, and application domain cannot be null");
        }
        String cachedIdTokenKey = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_TYPE_ID);
        String cachedAccessTokenKey = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_TYPE_ACCESS);
        String cachedRefreshTokenKey = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_TYPE_REFRESH);
        String cachedTokenScopes = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_KEY_SCOPES);
        try {
            SharedPreferences localCache = context.getSharedPreferences(ClientConstants.APP_LOCAL_CACHE, Context.MODE_PRIVATE);
            Set<String> cachedScopes = localCache.getStringSet(cachedTokenScopes, new HashSet<String>());
            // Check if the requested scopes match scopes of the cached tokens.
            if (!cachedScopes.equals(scopes)) {
                return session;
            }
            // Scopes match, return the cached tokens
            IdToken idToken = new IdToken(localCache.getString(cachedIdTokenKey, null));
            AccessToken accessToken = new AccessToken(localCache.getString(cachedAccessTokenKey, null));
            RefreshToken refreshToken = new RefreshToken(localCache.getString(cachedRefreshTokenKey, null));
            session = new AuthUserSession(idToken, accessToken, refreshToken);
        } catch (Exception e) {
            Log.e(TAG, "Failed to read from SharedPreferences", e);
        }
    }
    return session;
}
Also used : InvalidParameterException(java.security.InvalidParameterException) IdToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.IdToken) RefreshToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.RefreshToken) SharedPreferences(android.content.SharedPreferences) AccessToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken) AuthUserSession(com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession) InvalidParameterException(java.security.InvalidParameterException)

Example 3 with AccessToken

use of com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken in project aws-sdk-android by aws-amplify.

the class LocalDataManager method getCachedSession.

/**
 * Returns cached tokens for a user as a {@link AuthUserSession}.
 * @param context Required: The host application {@link Context}.
 * @param clientId Required: Cognito App/Client Id.
 * @param username Required: The username.
 * @return {@link AuthUserSession}.
 */
public static AuthUserSession getCachedSession(final AWSKeyValueStore awsKeyValueStore, final Context context, final String clientId, final String username, final Set<String> scopes) {
    AuthUserSession session = new AuthUserSession(null, null, null);
    if (username != null) {
        if (context == null || clientId == null || clientId.isEmpty()) {
            throw new InvalidParameterException("Application context, and application domain cannot be null");
        }
        String cachedIdTokenKey = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_TYPE_ID);
        String cachedAccessTokenKey = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_TYPE_ACCESS);
        String cachedRefreshTokenKey = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_TYPE_REFRESH);
        String cachedTokenScopes = String.format(Locale.US, "%s.%s.%s.%s", ClientConstants.APP_LOCAL_CACHE_KEY_PREFIX, clientId, username, ClientConstants.TOKEN_KEY_SCOPES);
        try {
            String cachedSetString = awsKeyValueStore.get(cachedTokenScopes);
            Set<String> cachedScopes = setFromString(cachedSetString);
            // Check if the requested scopes match scopes of the cached tokens.
            if (!cachedScopes.equals(scopes)) {
                return session;
            }
            // Scopes match, return the cached tokens
            IdToken idToken = new IdToken(awsKeyValueStore.get(cachedIdTokenKey));
            AccessToken accessToken = new AccessToken(awsKeyValueStore.get(cachedAccessTokenKey));
            RefreshToken refreshToken = new RefreshToken(awsKeyValueStore.get(cachedRefreshTokenKey));
            session = new AuthUserSession(idToken, accessToken, refreshToken);
        } catch (Exception e) {
            Log.e(TAG, "Failed to read from SharedPreferences", e);
        }
    }
    return session;
}
Also used : InvalidParameterException(java.security.InvalidParameterException) IdToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.IdToken) RefreshToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.RefreshToken) AccessToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken) AuthUserSession(com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession) InvalidParameterException(java.security.InvalidParameterException)

Example 4 with AccessToken

use of com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken in project aws-sdk-android by aws-amplify.

the class AuthHttpResponseParser method parseHttpResponse.

/**
 * Parses the http response from Cognito service and extracts tokens.
 * <p>
 *     Throws {@link AuthInvalidGrantException when }
 * </p>
 * @param responseStr Required: Response from Cognito Service Token-Endpoint.
 * @return {@link AuthUserSession}.
 */
public static final AuthUserSession parseHttpResponse(String responseStr) {
    if (responseStr == null || responseStr.isEmpty()) {
        throw new AuthInvalidParameterException("Invalid (null) response from Amazon Cognito Auth endpoint");
    }
    AccessToken accessToken = new AccessToken(null);
    IdToken idToken = new IdToken(null);
    RefreshToken refreshToken = new RefreshToken(null);
    JSONObject responseJson;
    try {
        responseJson = new JSONObject(responseStr);
        if (responseJson.has(ClientConstants.DOMAIN_QUERY_PARAM_ERROR)) {
            String errorText = responseJson.getString(ClientConstants.DOMAIN_QUERY_PARAM_ERROR);
            if (ClientConstants.HTTP_RESPONSE_INVALID_GRANT.equals(errorText)) {
                throw new AuthInvalidGrantException(errorText);
            } else {
                throw new AuthServiceException(errorText);
            }
        }
        if (responseJson.has(ClientConstants.HTTP_RESPONSE_ACCESS_TOKEN)) {
            accessToken = new AccessToken(responseJson.getString(ClientConstants.HTTP_RESPONSE_ACCESS_TOKEN));
        }
        if (responseJson.has(ClientConstants.HTTP_RESPONSE_ID_TOKEN)) {
            idToken = new IdToken(responseJson.getString(ClientConstants.HTTP_RESPONSE_ID_TOKEN));
        }
        if (responseJson.has(ClientConstants.HTTP_RESPONSE_REFRESH_TOKEN)) {
            refreshToken = new RefreshToken(responseJson.getString(ClientConstants.HTTP_RESPONSE_REFRESH_TOKEN));
        }
    } catch (AuthInvalidGrantException invg) {
        throw invg;
    } catch (AuthServiceException seve) {
        throw seve;
    } catch (Exception e) {
        throw new AuthClientException(e.getMessage(), e);
    }
    return new AuthUserSession(idToken, accessToken, refreshToken);
}
Also used : IdToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.IdToken) AuthServiceException(com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthServiceException) RefreshToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.RefreshToken) JSONObject(org.json.JSONObject) AuthClientException(com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthClientException) AuthInvalidParameterException(com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthInvalidParameterException) AccessToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken) AuthInvalidGrantException(com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthInvalidGrantException) AuthUserSession(com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession) AuthServiceException(com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthServiceException) AuthInvalidParameterException(com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthInvalidParameterException) AuthInvalidGrantException(com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthInvalidGrantException) AuthClientException(com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthClientException)

Example 5 with AccessToken

use of com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken in project aws-sdk-android by aws-amplify.

the class AWSMobileClientPersistenceWithRestartabilityTest method mockHostedUISignIn.

// Note that most tests create valid JWT tokens with expiry dates in the past. However, because
// we want to assert that HostedUI can get tokens, without making a network call to refresh a
// session, we're going to mock up valid session data, and ensure we call `getTokens` with
// `waitForSignIn = false`.
private void mockHostedUISignIn() throws JSONException {
    AuthUserSession authUserSession = new AuthUserSession(new IdToken(getValidJWT(3600L)), new AccessToken(getValidJWT(3600L)), new RefreshToken(getValidJWT(360000L)));
    Context targetContext = ApplicationProvider.getApplicationContext();
    AWSKeyValueStore storeForHostedUI = new AWSKeyValueStore(targetContext, "CognitoIdentityProviderCache", true);
    final Set<String> scopes = new HashSet<String>(Arrays.asList("aws.cognito.signin.user.admin", "phone", "openid", "profile", "email"));
    LocalDataManager.cacheSession(storeForHostedUI, targetContext, getPackageConfigure().getString("app_client_id"), getPackageConfigure().getString("username"), authUserSession, scopes);
    // Set the AWSMobileClient metadata that is specific to HostedUI
    auth.mStore.set(FEDERATION_ENABLED_KEY, "true");
    auth.mStore.set(HOSTED_UI_KEY, "dummyJson");
    auth.mStore.set(SIGN_IN_MODE, SignInMode.HOSTED_UI.toString());
    auth.mStore.set(PROVIDER_KEY, auth.getLoginKey());
    auth.mStore.set(TOKEN_KEY, getValidJWT(3600L));
}
Also used : Context(android.content.Context) IdToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.IdToken) RefreshToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.RefreshToken) AccessToken(com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken) AuthUserSession(com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession) AWSKeyValueStore(com.amazonaws.internal.keyvaluestore.AWSKeyValueStore) HashSet(java.util.HashSet)

Aggregations

AccessToken (com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken)5 IdToken (com.amazonaws.mobileconnectors.cognitoauth.tokens.IdToken)5 RefreshToken (com.amazonaws.mobileconnectors.cognitoauth.tokens.RefreshToken)5 AuthUserSession (com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession)4 InvalidParameterException (java.security.InvalidParameterException)2 Context (android.content.Context)1 SharedPreferences (android.content.SharedPreferences)1 AWSCredentials (com.amazonaws.auth.AWSCredentials)1 AWSKeyValueStore (com.amazonaws.internal.keyvaluestore.AWSKeyValueStore)1 SignInResult (com.amazonaws.mobile.client.results.SignInResult)1 Token (com.amazonaws.mobile.client.results.Token)1 Tokens (com.amazonaws.mobile.client.results.Tokens)1 AuthClientException (com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthClientException)1 AuthInvalidGrantException (com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthInvalidGrantException)1 AuthInvalidParameterException (com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthInvalidParameterException)1 AuthServiceException (com.amazonaws.mobileconnectors.cognitoauth.exceptions.AuthServiceException)1 UserNotConfirmedException (com.amazonaws.services.cognitoidentityprovider.model.UserNotConfirmedException)1 Date (java.util.Date)1 HashSet (java.util.HashSet)1 CountDownLatch (java.util.concurrent.CountDownLatch)1