Search in sources :

Example 1 with AuthenticationContinuation

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation in project aws-sdk-android by aws-amplify.

the class OAuth2Utils method _signIn.

private Runnable _signIn(final String username, final String password, final Map<String, String> validationData, final Map<String, String> clientMetadata, final AuthFlowType authFlowType, final Callback<SignInResult> callback) {
    this.signInCallback = callback;
    signInState = null;
    mStore.set(SIGN_IN_MODE, SignInMode.SIGN_IN.toString());
    return new Runnable() {

        @Override
        public void run() {
            try {
                userpool.getUser(username).getSession(clientMetadata, new AuthenticationHandler() {

                    @Override
                    public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
                        try {
                            mCognitoUserSession = userSession;
                            signInState = SignInState.DONE;
                        } catch (Exception e) {
                            signInCallback.onError(e);
                            signInCallback = null;
                        }
                        try {
                            if (isFederationEnabled()) {
                                federatedSignInWithoutAssigningState(userpoolsLoginKey, mCognitoUserSession.getIdToken().getJWTToken());
                            }
                            releaseSignInWait();
                        } catch (Exception e) {
                            Log.w(TAG, "Failed to federate tokens during sign-in", e);
                        } finally {
                            setUserState(new UserStateDetails(UserState.SIGNED_IN, getSignInDetailsMap()));
                        }
                        signInCallback.onResult(SignInResult.DONE);
                    }

                    @Override
                    public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
                        Log.d(TAG, "Sending password.");
                        final HashMap<String, String> authParameters = new HashMap<>();
                        // Check if the auth flow type setting is in the configuration.
                        boolean authFlowTypeInConfig = awsConfiguration.optJsonObject(AUTH_KEY) != null && awsConfiguration.optJsonObject(AUTH_KEY).has("authenticationFlowType");
                        try {
                            String resolvedAuthFlowType = authFlowType != null ? authFlowType.name() : null;
                            if (resolvedAuthFlowType == null && authFlowTypeInConfig) {
                                resolvedAuthFlowType = awsConfiguration.optJsonObject(AUTH_KEY).getString("authenticationFlowType");
                            }
                            if (resolvedAuthFlowType != null && AUTH_TYPE_INIT_CUSTOM_AUTH.equals(resolvedAuthFlowType)) {
                                // use one of the below constructors depending on what's passed in.
                                if (password != null) {
                                    authenticationContinuation.setAuthenticationDetails(new AuthenticationDetails(username, password, authParameters, validationData));
                                } else {
                                    authenticationContinuation.setAuthenticationDetails(new AuthenticationDetails(username, authParameters, validationData));
                                }
                            } else if (resolvedAuthFlowType != null && AUTH_TYPE_INIT_USER_PASSWORD.equals(resolvedAuthFlowType)) {
                                // If there's a value in the config and it's USER_PASSWORD_AUTH, set the auth type (challenge name)
                                // to be USER_PASSWORD.
                                AuthenticationDetails authenticationDetails = new AuthenticationDetails(username, password, validationData);
                                authenticationDetails.setAuthenticationType(CHLG_TYPE_USER_PASSWORD);
                                authenticationContinuation.setAuthenticationDetails(authenticationDetails);
                            } else {
                                // Otherwise, auth flow is USER_SRP_AUTH and the auth type (challenge name)
                                // will default to PASSWORD_VERIFIER.
                                Log.d(TAG, "Using USER_SRP_AUTH for flow type.");
                                authenticationContinuation.setAuthenticationDetails(new AuthenticationDetails(username, password, validationData));
                            }
                        } catch (JSONException exception) {
                            Log.w(TAG, "Exception while attempting to read authenticationFlowType from config.", exception);
                        }
                        authenticationContinuation.continueTask();
                    }

                    @Override
                    public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
                        signInMfaContinuation = continuation;
                        CognitoUserCodeDeliveryDetails parameters = continuation.getParameters();
                        signInState = SignInState.SMS_MFA;
                        signInCallback.onResult(new SignInResult(SignInState.SMS_MFA, new UserCodeDeliveryDetails(parameters.getDestination(), parameters.getDeliveryMedium(), parameters.getAttributeName())));
                    }

                    @Override
                    public void authenticationChallenge(ChallengeContinuation continuation) {
                        try {
                            signInState = SignInState.valueOf(continuation.getChallengeName());
                            signInChallengeContinuation = continuation;
                            signInCallback.onResult(new SignInResult(signInState, continuation.getParameters()));
                        } catch (IllegalArgumentException e) {
                            signInCallback.onError(e);
                        }
                    }

                    @Override
                    public void onFailure(Exception exception) {
                        signInCallback.onError(exception);
                    }
                });
            } catch (Exception e) {
                callback.onError(e);
            }
        }
    };
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) CognitoDevice(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice) CognitoUserCodeDeliveryDetails(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserCodeDeliveryDetails) UserCodeDeliveryDetails(com.amazonaws.mobile.client.results.UserCodeDeliveryDetails) 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) SignInResult(com.amazonaws.mobile.client.results.SignInResult) MultiFactorAuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation) CognitoUserCodeDeliveryDetails(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserCodeDeliveryDetails) MultiFactorAuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation) AuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation) ReturningRunnable(com.amazonaws.mobile.client.internal.ReturningRunnable) ChallengeContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.ChallengeContinuation) AuthenticationHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler) CognitoUserSession(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession) AuthenticationDetails(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationDetails)

Example 2 with AuthenticationContinuation

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation in project aws-sdk-android by aws-amplify.

the class AWSMobileClientTest method testRevokeTokenWithSignedOutUser.

@Test
public void testRevokeTokenWithSignedOutUser() throws Exception {
    auth.signIn(username, PASSWORD, null);
    assertTrue("isSignedIn is true", auth.isSignedIn());
    final CountDownLatch revokeTokenLatch = new CountDownLatch(1);
    final CognitoUser user = userPool.getCurrentUser();
    user.getSession(new AuthenticationHandler() {

        @Override
        public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
            revokeTokenLatch.countDown();
        }

        @Override
        public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
        }

        @Override
        public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
        }

        @Override
        public void authenticationChallenge(ChallengeContinuation continuation) {
        }

        @Override
        public void onFailure(Exception exception) {
            exception.printStackTrace();
            fail("Sign in failed.");
        }
    });
    revokeTokenLatch.await(5, TimeUnit.SECONDS);
    auth.signOut();
    assertFalse("isSignedIn is false", auth.isSignedIn());
    try {
        user.revokeTokens();
    } catch (Exception e) {
        assertTrue(e instanceof InvalidParameterException);
    }
}
Also used : MultiFactorAuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation) InvalidParameterException(com.amazonaws.services.cognitoidentityprovider.model.InvalidParameterException) MultiFactorAuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation) AuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation) CognitoDevice(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice) ChallengeContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.ChallengeContinuation) AuthenticationHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler) CountDownLatch(java.util.concurrent.CountDownLatch) CognitoUserSession(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession) CognitoUser(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser) UsernameExistsException(com.amazonaws.services.cognitoidentityprovider.model.UsernameExistsException) JSONException(org.json.JSONException) UserNotConfirmedException(com.amazonaws.services.cognitoidentityprovider.model.UserNotConfirmedException) NotAuthorizedException(com.amazonaws.services.cognitoidentityprovider.model.NotAuthorizedException) ResourceNotFoundException(com.amazonaws.services.cognitoidentityprovider.model.ResourceNotFoundException) InvalidParameterException(com.amazonaws.services.cognitoidentityprovider.model.InvalidParameterException) Test(org.junit.Test)

Example 3 with AuthenticationContinuation

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation in project aws-sdk-android by aws-amplify.

the class AWSMobileClientAuthFlowSettingTest method setupMockContinuation.

private AuthenticationContinuation setupMockContinuation() {
    AuthenticationContinuation mockContinuation = mock(AuthenticationContinuation.class);
    doAnswer(invocation -> {
        Log.i(TAG, "Counting down continuation latch.");
        continuationLatch.countDown();
        continuationComplete.set(true);
        return null;
    }).when(mockContinuation).continueTask();
    return mockContinuation;
}
Also used : AuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation)

Example 4 with AuthenticationContinuation

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation in project aws-sdk-android by aws-amplify.

the class AWSMobileClientAuthFlowSettingTest method verifyScenario.

/**
 * Verify that the correct auth type (aka challenge name) is passed in based on the
 * auth flow type from the config file.
 * @param configAuthFlowType The auth flow type from the config.
 * @param expectedAuthType The auth type expected.
 * @param overridenAuthFlowType The authType passed to the API
 * @throws JSONException Not expected.
 * @throws InterruptedException Not expected.
 */
private void verifyScenario(String configAuthFlowType, String overridenAuthFlowType, String expectedAuthType) throws JSONException, InterruptedException {
    AuthenticationContinuation mockContinuation = setupMockContinuation();
    CognitoUserPool mockUserPool = setupMockUserPool(mockContinuation);
    initMobileClientAndWait(configAuthFlowType, mockUserPool);
    signinAndWait(overridenAuthFlowType);
    ArgumentCaptor<AuthenticationDetails> argumentCaptor = ArgumentCaptor.forClass(AuthenticationDetails.class);
    verify(mockContinuation).setAuthenticationDetails(argumentCaptor.capture());
    AuthenticationDetails actualAuthDetails = argumentCaptor.getValue();
    assertEquals(expectedAuthType, actualAuthDetails.getAuthenticationType());
}
Also used : CognitoUserPool(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserPool) AuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation) AuthenticationDetails(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationDetails)

Example 5 with AuthenticationContinuation

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation in project aws-sdk-android by aws-amplify.

the class CognitoUser method getSessionInBackground.

/**
 * getSession orchestrates the SignIn flow with Amazon Cognito UserPools.
 *
 * <p>
 *     This method is asynchronous and performs network operations
 *     on a background thread.
 * </p>
 *
 * <p>
 *     1) Read the tokens (Id, Access and Refresh) that are cached on the device.
 *      1.1) If the Id and Access tokens are present and they are valid, the
 *          {@link AuthenticationHandler#onSuccess(CognitoUserSession, CognitoDevice)}.
 *          will be called with a {@link CognitoUserSession} that has references to the valid tokens.
 *          This means that the user is signed-in.
 *      1.2) If the Id and Access tokens are expired, and if there is a valid refresh token,
 *          a network call is made to get new Id and Access tokens.
 *          If valid Id and Access tokens are retrieved, they are cached on the device
 *          and {@link AuthenticationHandler#onSuccess(CognitoUserSession, CognitoDevice)}
 *          will be called with a {@link CognitoUserSession} that has references to the valid
 *          tokens. This means that the user is signed-in.
 *
 *     2) If there are no valid tokens cached on the device, the callback method
 *          {@link AuthenticationHandler#getAuthenticationDetails(AuthenticationContinuation, String)}
 *          will be called where the {@link AuthenticationDetails} will need to be supplied
 *          to continue the SignIn operation. See
 *          {@link com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.CognitoIdentityProviderContinuation}
 *          for details on continuation objects.
 *
 *     3) In all other error scenarios, {@link AuthenticationHandler#onFailure(Exception)} will
 *          be called with the type and message of the exception and it is the responsibility of
 *          the caller to handle the exceptions appropriately.
 * </p>
 *
 * @param callback REQUIRED: {@link AuthenticationHandler} callback
 */
public void getSessionInBackground(final AuthenticationHandler callback) {
    if (callback == null) {
        throw new CognitoParameterInvalidException("callback is null");
    }
    final CognitoUser cognitoUser = this;
    new Thread(new Runnable() {

        @Override
        public void run() {
            final Handler handler = new Handler(context.getMainLooper());
            Runnable returnCallback;
            try {
                getCachedSession();
                returnCallback = new Runnable() {

                    @Override
                    public void run() {
                        callback.onSuccess(cipSession, null);
                    }
                };
            } catch (final CognitoNotAuthorizedException e) {
                returnCallback = new Runnable() {

                    @Override
                    public void run() {
                        final AuthenticationContinuation authenticationContinuation = new AuthenticationContinuation(cognitoUser, context, AuthenticationContinuation.RUN_IN_BACKGROUND, callback);
                        callback.getAuthenticationDetails(authenticationContinuation, cognitoUser.getUserId());
                    }
                };
            } catch (final Exception e) {
                returnCallback = new Runnable() {

                    @Override
                    public void run() {
                        callback.onFailure(e);
                    }
                };
            }
            handler.post(returnCallback);
        }
    }).start();
}
Also used : CognitoParameterInvalidException(com.amazonaws.mobileconnectors.cognitoidentityprovider.exceptions.CognitoParameterInvalidException) MultiFactorAuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation) AuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation) CognitoNotAuthorizedException(com.amazonaws.mobileconnectors.cognitoidentityprovider.exceptions.CognitoNotAuthorizedException) Handler(android.os.Handler) GetDetailsHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GetDetailsHandler) AuthenticationHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler) GenericHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GenericHandler) VerificationHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.VerificationHandler) UpdateAttributesHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.UpdateAttributesHandler) ForgotPasswordHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.ForgotPasswordHandler) RegisterMfaHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.RegisterMfaHandler) DevicesHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.DevicesHandler) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CognitoInternalErrorException(com.amazonaws.mobileconnectors.cognitoidentityprovider.exceptions.CognitoInternalErrorException) UserNotFoundException(com.amazonaws.services.cognitoidentityprovider.model.UserNotFoundException) CognitoParameterInvalidException(com.amazonaws.mobileconnectors.cognitoidentityprovider.exceptions.CognitoParameterInvalidException) NotAuthorizedException(com.amazonaws.services.cognitoidentityprovider.model.NotAuthorizedException) ResourceNotFoundException(com.amazonaws.services.cognitoidentityprovider.model.ResourceNotFoundException) InvalidParameterException(com.amazonaws.services.cognitoidentityprovider.model.InvalidParameterException) CognitoNotAuthorizedException(com.amazonaws.mobileconnectors.cognitoidentityprovider.exceptions.CognitoNotAuthorizedException)

Aggregations

AuthenticationContinuation (com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation)19 MultiFactorAuthenticationContinuation (com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation)17 AuthenticationHandler (com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler)14 ChallengeContinuation (com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.ChallengeContinuation)13 CognitoDevice (com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice)10 CognitoUserSession (com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession)10 AuthenticationDetails (com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationDetails)10 InvalidParameterException (com.amazonaws.services.cognitoidentityprovider.model.InvalidParameterException)7 NotAuthorizedException (com.amazonaws.services.cognitoidentityprovider.model.NotAuthorizedException)7 ResourceNotFoundException (com.amazonaws.services.cognitoidentityprovider.model.ResourceNotFoundException)7 HashMap (java.util.HashMap)7 Test (org.junit.Test)6 CognitoInternalErrorException (com.amazonaws.mobileconnectors.cognitoidentityprovider.exceptions.CognitoInternalErrorException)5 CognitoNotAuthorizedException (com.amazonaws.mobileconnectors.cognitoidentityprovider.exceptions.CognitoNotAuthorizedException)5 CognitoParameterInvalidException (com.amazonaws.mobileconnectors.cognitoidentityprovider.exceptions.CognitoParameterInvalidException)5 InitiateAuthRequest (com.amazonaws.services.cognitoidentityprovider.model.InitiateAuthRequest)5 UserNotFoundException (com.amazonaws.services.cognitoidentityprovider.model.UserNotFoundException)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 FlowTracker (com.amazonaws.mobileconnectors.cognitoidentityprovider.utils.FlowTracker)4 RespondToAuthChallengeRequest (com.amazonaws.services.cognitoidentityprovider.model.RespondToAuthChallengeRequest)4