Search in sources :

Example 1 with AuthUserSession

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

the class OAuth2Utils method _showSignInHostedUI.

private Runnable _showSignInHostedUI(final Activity callingActivity, final SignInUIOptions signInUIOptions, final Callback<UserStateDetails> callback) {
    return new Runnable() {

        @Override
        public void run() {
            final HostedUIOptions hostedUIOptions = signInUIOptions.getHostedUIOptions();
            // Reset settings to JSON
            JSONObject hostedUIJSON = null;
            try {
                hostedUIJSON = new JSONObject(getHostedUIJSONFromJSON().toString());
            } catch (JSONException e) {
                callback.onError(new Exception("Could not create OAuth configuration object", e));
            }
            if (hostedUIOptions.getFederationEnabled() != null) {
                mStore.set(FEDERATION_ENABLED_KEY, hostedUIOptions.getFederationEnabled() ? "true" : "false");
            } else {
                mStore.set(FEDERATION_ENABLED_KEY, "true");
            }
            if (hostedUIOptions.getSignOutQueryParameters() != null) {
                try {
                    JSONObject signOutParams = new JSONObject();
                    for (Map.Entry<String, String> e : hostedUIOptions.getSignOutQueryParameters().entrySet()) {
                        signOutParams.put(e.getKey(), e.getValue());
                    }
                    hostedUIJSON.put("SignOutQueryParameters", signOutParams);
                } catch (JSONException e1) {
                    callback.onError(new Exception("Failed to construct sign-out query parameters", e1));
                    return;
                }
            }
            if (hostedUIOptions.getTokenQueryParameters() != null) {
                try {
                    JSONObject tokenParams = new JSONObject();
                    for (Map.Entry<String, String> e : hostedUIOptions.getTokenQueryParameters().entrySet()) {
                        tokenParams.put(e.getKey(), e.getValue());
                    }
                    hostedUIJSON.put("TokenQueryParameters", tokenParams);
                } catch (JSONException e1) {
                    callback.onError(new Exception("Failed to construct token query parameters", e1));
                    return;
                }
            }
            mStore.set(HOSTED_UI_KEY, hostedUIJSON.toString());
            final HashSet<String> scopes;
            if (hostedUIOptions.getScopes() != null) {
                scopes = new HashSet<String>();
                Collections.addAll(scopes, hostedUIOptions.getScopes());
            } else {
                scopes = null;
            }
            final String identityProvider = hostedUIOptions.getIdentityProvider();
            final String idpIdentifier = hostedUIOptions.getIdpIdentifier();
            mStore.set(SIGN_IN_MODE, SignInMode.HOSTED_UI.toString());
            Auth.Builder hostedUIBuilder = null;
            try {
                hostedUIBuilder = getHostedUI(hostedUIJSON);
            } catch (JSONException e) {
                throw new RuntimeException("Failed to construct HostedUI from awsconfiguration.json", e);
            }
            hostedUIBuilder.setPersistenceEnabled(mIsPersistenceEnabled).setAuthHandler(new AuthHandler() {

                boolean hasSucceededOnce = false;

                @Override
                public void onSuccess(AuthUserSession session) {
                    Log.d(TAG, "onSuccess: HostedUI signed-in");
                    hasSucceededOnce = true;
                    if (isFederationEnabled()) {
                        federatedSignInWithoutAssigningState(userpoolsLoginKey, session.getIdToken().getJWTToken(), new Callback<UserStateDetails>() {

                            @Override
                            public void onResult(UserStateDetails result) {
                                Log.d(TAG, "onResult: Federation from the Hosted UI " + "succeeded");
                            }

                            @Override
                            public void onError(Exception e) {
                                Log.e(TAG, "onError: Federation from the Hosted UI " + "failed", e);
                            }
                        });
                    }
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            final UserStateDetails userStateDetails = getUserStateDetails(false);
                            callback.onResult(userStateDetails);
                            setUserState(userStateDetails);
                        }
                    }).start();
                }

                @Override
                public void onSignout() {
                    Log.d(TAG, "onSignout: HostedUI signed-out");
                }

                @Override
                public void onFailure(final Exception e) {
                    if (hasSucceededOnce) {
                        Log.d(TAG, "onFailure: Ignoring failure because HostedUI " + "has signaled success at least once.");
                        return;
                    }
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            callback.onError(e);
                        }
                    }).start();
                }
            });
            if (scopes != null) {
                hostedUIBuilder.setScopes(scopes);
            }
            if (identityProvider != null) {
                hostedUIBuilder.setIdentityProvider(identityProvider);
            }
            if (idpIdentifier != null) {
                hostedUIBuilder.setIdpIdentifier(idpIdentifier);
            }
            hostedUI = hostedUIBuilder.build();
            if (signInUIOptions.getBrowserPackage() != null) {
                hostedUI.setBrowserPackage(signInUIOptions.getBrowserPackage());
            }
            hostedUI.getSession(callingActivity);
        }
    };
}
Also used : AuthHandler(com.amazonaws.mobileconnectors.cognitoauth.handlers.AuthHandler) JSONException(org.json.JSONException) JSONException(org.json.JSONException) InvalidUserPoolConfigurationException(com.amazonaws.services.cognitoidentityprovider.model.InvalidUserPoolConfigurationException) AmazonClientException(com.amazonaws.AmazonClientException) NotAuthorizedException(com.amazonaws.services.cognitoidentity.model.NotAuthorizedException) WorkerThread(androidx.annotation.WorkerThread) AnyThread(androidx.annotation.AnyThread) CustomTabsCallback(androidx.browser.customtabs.CustomTabsCallback) InternalCallback(com.amazonaws.mobile.client.internal.InternalCallback) JSONObject(org.json.JSONObject) ReturningRunnable(com.amazonaws.mobile.client.internal.ReturningRunnable) Auth(com.amazonaws.mobileconnectors.cognitoauth.Auth) AuthUserSession(com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Example 2 with AuthUserSession

use of com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession 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 AuthUserSession

use of com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession 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 AuthUserSession

use of com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession 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 AuthUserSession

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

the class OAuth2Utils method _getHostedUITokens.

private void _getHostedUITokens(final Callback<Tokens> callback) {
    hostedUI = hostedUI.getCurrentUser();
    hostedUI.setAuthHandler(new AuthHandler() {

        @Override
        public void onSuccess(AuthUserSession session) {
            callback.onResult(new Tokens(session.getAccessToken().getJWTToken(), session.getIdToken().getJWTToken(), session.getRefreshToken().getToken()));
        }

        @Override
        public void onSignout() {
            callback.onError(new Exception("No cached session."));
        }

        @Override
        public void onFailure(Exception e) {
            callback.onError(new Exception("No cached session.", e));
        }
    });
    hostedUI.getSessionWithoutWebUI();
}
Also used : AuthHandler(com.amazonaws.mobileconnectors.cognitoauth.handlers.AuthHandler) AuthUserSession(com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession) JSONException(org.json.JSONException) InvalidUserPoolConfigurationException(com.amazonaws.services.cognitoidentityprovider.model.InvalidUserPoolConfigurationException) AmazonClientException(com.amazonaws.AmazonClientException) NotAuthorizedException(com.amazonaws.services.cognitoidentity.model.NotAuthorizedException) Tokens(com.amazonaws.mobile.client.results.Tokens) OAuth2Tokens(com.amazonaws.mobile.client.internal.oauth2.OAuth2Tokens)

Aggregations

AuthUserSession (com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession)7 AccessToken (com.amazonaws.mobileconnectors.cognitoauth.tokens.AccessToken)4 IdToken (com.amazonaws.mobileconnectors.cognitoauth.tokens.IdToken)4 RefreshToken (com.amazonaws.mobileconnectors.cognitoauth.tokens.RefreshToken)4 AmazonClientException (com.amazonaws.AmazonClientException)3 AuthHandler (com.amazonaws.mobileconnectors.cognitoauth.handlers.AuthHandler)3 NotAuthorizedException (com.amazonaws.services.cognitoidentity.model.NotAuthorizedException)3 InvalidUserPoolConfigurationException (com.amazonaws.services.cognitoidentityprovider.model.InvalidUserPoolConfigurationException)3 JSONException (org.json.JSONException)3 InvalidParameterException (java.security.InvalidParameterException)2 HashSet (java.util.HashSet)2 JSONObject (org.json.JSONObject)2 Context (android.content.Context)1 SharedPreferences (android.content.SharedPreferences)1 AnyThread (androidx.annotation.AnyThread)1 WorkerThread (androidx.annotation.WorkerThread)1 CustomTabsCallback (androidx.browser.customtabs.CustomTabsCallback)1 AWSKeyValueStore (com.amazonaws.internal.keyvaluestore.AWSKeyValueStore)1 InternalCallback (com.amazonaws.mobile.client.internal.InternalCallback)1 ReturningRunnable (com.amazonaws.mobile.client.internal.ReturningRunnable)1