Search in sources :

Example 71 with AWSCredentials

use of com.amazonaws.auth.AWSCredentials 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 72 with AWSCredentials

use of com.amazonaws.auth.AWSCredentials in project aws-sdk-android by aws-amplify.

the class AWSMobileClientPersistenceWithRestartabilityTest method testGetCredentials.

@Test
public void testGetCredentials() {
    signInAndVerifySignIn();
    AWSCredentials awsCredentialsBeforeEncryptionKeysAreLost = auth.getCredentials();
    assertNotNull(awsCredentialsBeforeEncryptionKeysAreLost);
    deleteAllEncryptionKeys();
    initializeAWSMobileClient(appContext, UserState.SIGNED_OUT);
    AWSCredentials awsCredentialsAfterEncryptionKeysAreLost = auth.getCredentials();
    assertNotNull(awsCredentialsAfterEncryptionKeysAreLost);
    assertEquals(awsCredentialsBeforeEncryptionKeysAreLost.getAWSAccessKeyId(), awsCredentialsAfterEncryptionKeysAreLost.getAWSAccessKeyId());
    assertEquals(awsCredentialsBeforeEncryptionKeysAreLost.getAWSSecretKey(), awsCredentialsAfterEncryptionKeysAreLost.getAWSSecretKey());
}
Also used : AWSCredentials(com.amazonaws.auth.AWSCredentials) Test(org.junit.Test)

Example 73 with AWSCredentials

use of com.amazonaws.auth.AWSCredentials in project aws-sdk-android by aws-amplify.

the class AWSMobileClientTest method testSignInWaitFederated.

@Test
public void testSignInWaitFederated() throws Exception {
    final AtomicReference<Boolean> hasWaited = new AtomicReference<Boolean>();
    hasWaited.set(false);
    setTokensDirectly(appContext, "fakeProvider", "fakeToken", "someIdentityId");
    listener = new UserStateListener() {

        @Override
        public void onUserStateChanged(UserStateDetails details) {
            switch(details.getUserState()) {
                case SIGNED_OUT_FEDERATED_TOKENS_INVALID:
                    try {
                        hasWaited.set(true);
                        auth.signIn(getPackageConfigure().getString("username"), PASSWORD, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        fail("Sign-in failed, but not expected.");
                    }
                    break;
            }
        }
    };
    auth.addUserStateListener(listener);
    AWSCredentials credentials = auth.getCredentials();
    assertNotNull(credentials);
    assertNotNull(credentials.getAWSAccessKeyId());
    assertNotNull(credentials.getAWSSecretKey());
    assertTrue("Should have waited, but didn't", hasWaited.get());
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) AWSCredentials(com.amazonaws.auth.AWSCredentials) 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 74 with AWSCredentials

use of com.amazonaws.auth.AWSCredentials in project aws-sdk-android by aws-amplify.

the class AWSMobileClientTest method testSignOut.

@Test
public void testSignOut() throws Exception {
    final SignInResult signInResult = auth.signIn(username, PASSWORD, null);
    assertEquals("Cannot support MFA in tests", SignInState.DONE, signInResult.getSignInState());
    AWSCredentials credentials1 = auth.getCredentials();
    auth.signOut();
    // Test identity id has been cleared
    assertNull(auth.getIdentityId());
    // Test username has been cleared
    assertNull(auth.getUsername());
    // Check credentials need to be fetched
    try {
        AWSCredentials credentials = auth.getCredentials();
        fail("Unauthenticated access is not supported for this identity pool in this test\n" + credentials.getAWSAccessKeyId() + "\n" + credentials1.getAWSAccessKeyId());
    } catch (RuntimeException e) {
        assertTrue(e.getCause() instanceof com.amazonaws.services.cognitoidentity.model.NotAuthorizedException);
    }
    // Check tokens are gone
    try {
        assertNull(auth.getTokens());
    } catch (Exception e) {
        assertEquals("getTokens does not support retrieving tokens while signed-out", e.getMessage());
    }
}
Also used : NotAuthorizedException(com.amazonaws.services.cognitoidentityprovider.model.NotAuthorizedException) AWSCredentials(com.amazonaws.auth.AWSCredentials) 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) SignInResult(com.amazonaws.mobile.client.results.SignInResult) Test(org.junit.Test)

Example 75 with AWSCredentials

use of com.amazonaws.auth.AWSCredentials in project aws-sdk-android by aws-amplify.

the class AWSMobileClientCustomAuthTest method testCustomAuth.

/**
 * This test needs following backend set up to complete successfully :
 *
 * User - This test assumes presence of a user named `customAuthTestUser` in the test user pool
 * App Client - There should be an app client with "Only allow Custom Authentication (CUSTOM_AUTH_FLOW_ONLY)" enabled.
 * Lambda Triggers - It needs following lambda triggers set in the test userpool:
 *   Define Auth Lambda Trigger :
 *     ```
 *     exports.handler = function(event, context) {
 *         if (event.request.session.length == 1 && event.request.session[0].challengeName == 'SRP_A') {
 *             event.response.issueTokens = false;
 *             event.response.failAuthentication = false;
 *             event.response.challengeName = 'CUSTOM_CHALLENGE';
 *         } else if (event.request.session.length == 2 && event.request.session[1].challengeName == 'CUSTOM_CHALLENGE' && event.request.session[1].challengeResult == true) {
 *             event.response.issueTokens = true;
 *             event.response.failAuthentication = false;
 *             event.response.challengeName = 'CUSTOM_CHALLENGE';
 *         } else {
 *             event.response.issueTokens = false;
 *             event.response.failAuthentication = true;
 *         }
 *         context.done(null, event);
 *     }
 *     ```
 *
 *   Create Auth Lambda Trigger :
 *     ```
 *     function createAuthChallenge(event) {
 *         if (event.request.challengeName === 'CUSTOM_CHALLENGE') {
 *             event.response.publicChallengeParameters = {};
 *             event.response.privateChallengeParameters = {};
 *             event.response.privateChallengeParameters.answer = '1133';
 *         }
 *     }
 *
 *     exports.handler = (event, context, callback) => {
 *         console.log(JSON.stringify(event));
 *         createAuthChallenge(event);
 *
 *         console.log(JSON.stringify(event));
 *         callback(null, event);
 *     };
 *     ```
 *
 *   Verify Auth Lambda Trigger :
 *     ```
 *     function verifyAuthChallengeResponse(event) {
 *         if (event.request.privateChallengeParameters.answer === event.request.challengeAnswer) {
 *             event.response.answerCorrect = true;
 *         } else {
 *             event.response.answerCorrect = false;
 *         }
 *     }
 *
 *     exports.handler = (event, context, callback) => {
 *         console.log(JSON.stringify(event));
 *             verifyAuthChallengeResponse(event);
 *
 *         console.log(JSON.stringify(event));
 *         callback(null, event);
 *     };
 *     ```
 * awsconfiguration.json - Should set authenticationFlowType to 'CUSTOM_AUTH' in Auth section as follows :
 *
 *     ```
 *     "Auth": {
 *         "Default": {
 *             "authenticationFlowType": "CUSTOM_AUTH"
 *         }
 *     }
 *     ```
 *
 * @throws Exception
 */
@Test
public void testCustomAuth() throws Exception {
    // Check successful sign In
    assertTrue("SignIn successful", signIn());
    // 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);
}
Also used : Token(com.amazonaws.mobile.client.results.Token) AWSCredentials(com.amazonaws.auth.AWSCredentials) Date(java.util.Date) Tokens(com.amazonaws.mobile.client.results.Tokens) Test(org.junit.Test)

Aggregations

AWSCredentials (com.amazonaws.auth.AWSCredentials)201 BasicAWSCredentials (com.amazonaws.auth.BasicAWSCredentials)119 AWSStaticCredentialsProvider (com.amazonaws.auth.AWSStaticCredentialsProvider)50 Test (org.junit.Test)48 AWSCredentialsProvider (com.amazonaws.auth.AWSCredentialsProvider)45 ClientConfiguration (com.amazonaws.ClientConfiguration)35 AmazonClientException (com.amazonaws.AmazonClientException)28 AmazonS3Client (com.amazonaws.services.s3.AmazonS3Client)26 ProfileCredentialsProvider (com.amazonaws.auth.profile.ProfileCredentialsProvider)15 AmazonS3 (com.amazonaws.services.s3.AmazonS3)13 Date (java.util.Date)13 IOException (java.io.IOException)12 AmazonServiceException (com.amazonaws.AmazonServiceException)11 AWSSessionCredentials (com.amazonaws.auth.AWSSessionCredentials)11 BasicSessionCredentials (com.amazonaws.auth.BasicSessionCredentials)11 PropertiesCredentials (com.amazonaws.auth.PropertiesCredentials)11 File (java.io.File)11 Properties (java.util.Properties)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 AnonymousAWSCredentials (com.amazonaws.auth.AnonymousAWSCredentials)9