Search in sources :

Example 11 with AuthenticationHandler

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler in project aws-sdk-android by aws-amplify.

the class CognitoUserPoolsIntegrationTestBase method signIn.

CognitoUserSession signIn() {
    final CountDownLatch signInLatch = new CountDownLatch(1);
    final ArrayList<CognitoUserSession> listSessions = new ArrayList<CognitoUserSession>();
    cognitoUserPool.getUser(userName).getSession(new AuthenticationHandler() {

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

        @Override
        public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
            AuthenticationDetails authenticationDetails = new AuthenticationDetails(userName, password, null);
            authenticationContinuation.setAuthenticationDetails(authenticationDetails);
            authenticationContinuation.continueTask();
        }

        @Override
        public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
            fail("Tests are not configured to work with MFA. " + "Either create a CognitoUserPool without MFA or update the test.");
            signInLatch.countDown();
        }

        @Override
        public void authenticationChallenge(ChallengeContinuation continuation) {
            fail("Tests are not configured to work with additional challenges. " + "Either create a CognitoUserPool without additional challenges or update the test.");
            signInLatch.countDown();
        }

        @Override
        public void onFailure(Exception exception) {
            fail("Error while signing-in. " + exception.getLocalizedMessage());
            signInLatch.countDown();
        }
    });
    try {
        signInLatch.await(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    assertEquals(1, listSessions.size());
    return listSessions.get(0);
}
Also used : ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) MultiFactorAuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation) AuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation) MultiFactorAuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation) ChallengeContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.ChallengeContinuation) AuthenticationHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler) AuthenticationDetails(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationDetails)

Example 12 with AuthenticationHandler

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler in project aws-sdk-android by aws-amplify.

the class AWSMobileClientTest method testRevokeTokenWithSignedInUser.

@Test
public void testRevokeTokenWithSignedInUser() throws Exception {
    auth.signIn(username, PASSWORD, null);
    assertTrue("isSignedIn is true", auth.isSignedIn());
    final AtomicReference<Boolean> tokenRevoked = new AtomicReference<Boolean>(false);
    final CountDownLatch revokeTokenLatch = new CountDownLatch(2);
    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.");
        }
    });
    user.getDetails(new GetDetailsHandler() {

        @Override
        public void onSuccess(CognitoUserDetails cognitoUserDetails) {
            revokeTokenLatch.countDown();
        }

        @Override
        public void onFailure(Exception exception) {
            exception.printStackTrace();
            fail("Get user details failed.");
        }
    });
    try {
        user.revokeTokens();
        tokenRevoked.set(true);
    } catch (Exception e) {
        e.printStackTrace();
    }
    revokeTokenLatch.await(5, TimeUnit.SECONDS);
    assertTrue(tokenRevoked.get());
    user.getDetails(new GetDetailsHandler() {

        @Override
        public void onSuccess(CognitoUserDetails cognitoUserDetails) {
            fail("Request to get user details should fail with NotAuthorizedException after token is revoked.");
        }

        @Override
        public void onFailure(Exception exception) {
            assertTrue(exception instanceof NotAuthorizedException);
        }
    });
}
Also used : CognitoDevice(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice) CognitoUserDetails(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserDetails) AtomicReference(java.util.concurrent.atomic.AtomicReference) NotAuthorizedException(com.amazonaws.services.cognitoidentityprovider.model.NotAuthorizedException) CountDownLatch(java.util.concurrent.CountDownLatch) 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) MultiFactorAuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation) MultiFactorAuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation) AuthenticationContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation) ChallengeContinuation(com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.ChallengeContinuation) AuthenticationHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler) CognitoUserSession(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession) CognitoUser(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser) GetDetailsHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GetDetailsHandler) Test(org.junit.Test)

Example 13 with AuthenticationHandler

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler in project aws-sdk-android by aws-amplify.

the class AuthenticationContinuationTest method setMetadataAndContinueTask.

/**
 * What happens when we try to pass client metadata into the handler?
 * @throws InterruptedException If {@link CountDownRunnable} is interrupted while pending result
 */
@Test
public void setMetadataAndContinueTask() throws InterruptedException {
    AuthenticationHandler handler = mock(AuthenticationHandler.class);
    CognitoUser user = mock(CognitoUser.class);
    AuthenticationDetails authenticationDetails = mock(AuthenticationDetails.class);
    Map<String, String> metadata = Collections.singletonMap("blacklives", "matter");
    AuthenticationContinuation authenticationContinuation = new AuthenticationContinuation(user, getApplicationContext(), false, handler);
    authenticationContinuation.setClientMetaData(metadata);
    authenticationContinuation.setAuthenticationDetails(authenticationDetails);
    CountDownRunnable countDownRunnable = CountDownRunnable.create();
    doReturn(countDownRunnable).when(user).initiateUserAuthentication(eq(metadata), eq(authenticationDetails), eq(handler), eq(false));
    // Act: continue task
    authenticationContinuation.continueTask();
    // Assert: action was invoked
    assertTrue(countDownRunnable.await(5, TimeUnit.SECONDS));
    assertEquals(metadata, authenticationContinuation.getClientMetaData());
}
Also used : AuthenticationHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler) CognitoUser(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser) Test(org.junit.Test)

Example 14 with AuthenticationHandler

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler in project aws-sdk-android by aws-amplify.

the class MultiFactorAuthenticationContinuationTest method setMetadataAndContinueTask.

/**
 * What happens when we try to pass client metadata into the handler?
 * @throws InterruptedException If {@link CountDownRunnable} is interrupted while pending result
 */
@Test
public void setMetadataAndContinueTask() throws InterruptedException {
    AuthenticationHandler handler = mock(AuthenticationHandler.class);
    CognitoUser user = mock(CognitoUser.class);
    String mfaCode = "mfa";
    Map<String, String> metadata = Collections.singletonMap("blacklives", "matter");
    RespondToAuthChallengeResult result = new RespondToAuthChallengeResult();
    MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation = new MultiFactorAuthenticationContinuation(user, getApplicationContext(), result, false, handler);
    multiFactorAuthenticationContinuation.setClientMetaData(metadata);
    multiFactorAuthenticationContinuation.setMfaCode(mfaCode);
    CountDownRunnable countDownRunnable = CountDownRunnable.create();
    doReturn(countDownRunnable).when(user).respondToMfaChallenge(eq(metadata), eq(mfaCode), eq(result), eq(handler), eq(false));
    // Act: continue task
    multiFactorAuthenticationContinuation.continueTask();
    // Assert: action was invoked
    assertTrue(countDownRunnable.await(5, TimeUnit.SECONDS));
    assertEquals(metadata, multiFactorAuthenticationContinuation.getClientMetaData());
}
Also used : RespondToAuthChallengeResult(com.amazonaws.services.cognitoidentityprovider.model.RespondToAuthChallengeResult) AuthenticationHandler(com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler) CognitoUser(com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser) Test(org.junit.Test)

Example 15 with AuthenticationHandler

use of com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler 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 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 authFlowType = authFlowTypeInConfig ? awsConfiguration.optJsonObject(AUTH_KEY).getString("authenticationFlowType") : null;
                            if (authFlowTypeInConfig && AUTH_TYPE_INIT_CUSTOM_AUTH.equals(authFlowType)) {
                                // 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 (authFlowTypeInConfig && AUTH_TYPE_INIT_USER_PASSWORD.equals(authFlowType)) {
                                // 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)

Aggregations

AuthenticationHandler (com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler)17 AuthenticationContinuation (com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation)14 MultiFactorAuthenticationContinuation (com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation)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)9 Test (org.junit.Test)9 HashMap (java.util.HashMap)7 CognitoUser (com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser)5 FlowTracker (com.amazonaws.mobileconnectors.cognitoidentityprovider.utils.FlowTracker)4 InitiateAuthRequest (com.amazonaws.services.cognitoidentityprovider.model.InitiateAuthRequest)4 InvalidParameterException (com.amazonaws.services.cognitoidentityprovider.model.InvalidParameterException)4 NotAuthorizedException (com.amazonaws.services.cognitoidentityprovider.model.NotAuthorizedException)4 ResourceNotFoundException (com.amazonaws.services.cognitoidentityprovider.model.ResourceNotFoundException)4 Map (java.util.Map)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 JSONException (org.json.JSONException)4 Ignore (org.junit.Ignore)4 ArgumentCaptor (org.mockito.ArgumentCaptor)4