Menu
Amazon Cognito
Developer Guide (Version Last Updated: 08/26/2017)

Tutorial: Integrating User Pools for Android Apps

This tutorial outlines the key steps to integrate Amazon Cognito Your User Pools with an Android application. For a complete sample application that shows how to use user pools in your application, see the Amazon Cognito Your User Pools sample on the GitHub website.

Step 1: Creating a User Pool for Your App by Using the Console

The following procedure describes how to create a user pool and use it in your app. This procedure creates a pool ID, an app client ID, and an app client secret using default settings. For information on customizing these settings, see Step Through Amazon Cognito User Pool Settings in the AWS Management Console.

To create a user pool for your app

  1. Sign in to the Amazon Cognito console

  2. Choose Manage your User Pools.

  3. Choose Create a User Pool.

  4. In Pool name, type a name for the pool and then choose Review defaults. This creates the pool with the default settings.

  5. From the left navigation pane, choose Attributes to specify which attributes are required and which attributes to use as aliases. After you set the following attributes and after users in the pool verify their email addresses, they can sign in with their usernames or email addresses.

    1. For email, choose Required and Alias.

    2. For phone number, choose Required and Alias.

    3. For given name, choose Required.

    4. Choose Save changes.

  6. From the left navigation pane, choose Policies to specify the password policy. For this tutorial, use the default settings.

  7. From the left navigation pane, choose Verifications. On this page, you can customize the messages that are sent to the users in your pool to deliver verification codes. For this tutorial, use the default settings.

  8. From the left navigation pane, choose Apps and then choose Add an app. You can create multiple app clients for a user pool and you can create one app per platform.

  9. For App name, type a name for your app. Keep Generate app client secret selected, and then choose Set attribute read and write permissions. Select the attributes that require write permissions. Required attributes always have write permissions.

  10. Choose Create app and then choose Save changes.

  11. From the left navigation bar, choose Review and then choose Create pool.

  12. Note the Pool ID, Pool ARN, App client ID, and App client secret. You can find the app client ID and app client secret under Apps on the left navigation bar. To view the client secret, choose Show details.

Step 2: Creating a User Pool Object

To create a user pool object, you need the pool ID, client ID, and client secret. The following example shows how to create a ClientConfiguration object and a CognitoUserPool object. The CognitoUserPool object is the entry point for all interactions with your user pool from your application. In the sample application the userPool is created in AppHelper.java.

Copy
ClientConfiguration clientConfiguration = new ClientConfiguration(); // Create a CognitoUserPool object to refer to your user pool CognitoUserPool userPool = new CognitoUserPool(context, poolId, clientId, clientSecret, clientConfiguration);

Step 3: Signing up Users for Your App

The following steps describe how to sign up users for your app.

To sign up users for your app

  1. Collect the following information from the user:

    • user-id: This is used by the user to log in and must be unique within the pool.

    • password: This is the user’s password.

    • user attributes: You must specify the required attributes (email, given name, and phone number) for your pool.

  2. Use the pool instance to sign up the user.

    Copy
    // Create a CognitoUserAttributes object and add user attributes CognitoUserAttributes userAttributes = new CognitoUserAttributes(); // Add the user attributes. Attributes are added as key-value pairs // Adding user's given name. // Note that the key is "given_name" which is the OIDC claim for given name userAttributes.addAttribute("given_name", userGivenName); // Adding user's phone number userAttributes.addAttribute("phone_number", phoneNumber); // Adding user's email address userAttributes.addAttribute("email", emailAddress);
  3. Create a callback handler for sign-up. The onSuccess method is called when the sign-up is successful.

    Copy
    SignUpHandler signupCallback = new SignUpHandler() { @Override public void onSuccess(CognitoUser cognitoUser, boolean userConfirmed, CognitoUserCodeDeliveryDetails cognitoUserCodeDeliveryDetails) { // Sign-up was successful // Check if this user (cognitoUser) needs to be confirmed if(!userConfirmed) { // This user must be confirmed and a confirmation code was sent to the user // cognitoUserCodeDeliveryDetails will indicate where the confirmation code was sent // Get the confirmation code from user } else { // The user has already been confirmed } } @Override public void onFailure(Exception exception) { // Sign-up failed, check exception for the cause } };
  4. Call the sign-up API.

    Copy
    userPool.signUpInBackground(userId, password, userAttributes, null, signupCallback);

Step 4: Confirming Users for Your App

Users may need to be confirmed after they sign up before they can sign in. Users can confirm through email or phone. After a successful sign-up, if the user needs to be confirmed, a confirmation code is sent to the user's email address or phone number. You can also automatically confirm a user after sign-up by using Lambda triggers.

If a user provides an email address or phone number during sign-up, and you selected automatic verification for your user pool, a confirmation code is sent to the user's phone number as a text message or to the user's email address. The cognitoUserCodeDeliveryDetails object, which was delivered to the callback handler after successful sign-up, indicates where this confirmation code was sent. You can use this to let the user know how he or she will get confirmation code.

The following steps describe how to confirm user information before users can sign in to your app.

To confirm a user for your app

  1. Create a callback handler to confirm the user. This callback handler is used by the SDK to communicate the results of the confirmation API call.

    Copy
    // Callback handler for confirmSignUp API GenericHandler confirmationCallback = new GenericHandler() { @Override public void onSuccess() { // User was successfully confirmed } @Override public void onFailure(Exception exception) { // User confirmation failed. Check exception for the cause. } };
  2. When a new user is confirmed, the user's attribute through which the confirmation code was sent (email address or phone number) is marked as verified. If this attribute is also set to be used as an alias, then the user can sign in with that attribute (email address or phone number) instead of the username.

Step 5: Resolving Alias Value Conflicts

Alias values must be unique in a pool. When you confirm a new user, if that user's email address or phone number are used as an alias, and that email or phone number are already in use for an existing user in the pool, you must resolve this conflict. To ensure uniqueness, you can do either of the following:

  • Set the forcedAliasCreation parameter to false. This resolves the conflict by allowing the user confirmation to fail. The attribute remains verified for the existing user and continues to be an alias for the existing user. The new user remains un-confirmed, as shown in the following example.

    Copy
    // This will cause confirmation to fail if the user attribute has been verified for another user in the same pool boolean forcedAliasCreation = false; // Call API to confirm this user cognitoUser.confirmSignUpInBackground(confirmationCode, forcedAliasCreation, confirmationCallback);
  • Setting the forcedAliasCreation parameter to true resolves the conflict by marking the attribute (email or phone number) as verified for the new user, and consequently marking it as not-verified for the existing user. This attribute is no longer an alias for the existing user.

All confirmed users can sign in. On successful sign-in, access and ID tokens are returned. These tokens are in a CognitoUserSession object.

Step 6: Signing Users in to Your App

To sign a user in to your app, you must first create a callback handler for authentication. The following example shows how the SDK interacts with your application through this callback handler.

Copy
// Callback handler for the sign-in process AuthenticationHandler authenticationHandler = new AuthenticationHandler() { @Override public void onSuccess(CognitoUserSession cognitoUserSession) { // Sign-in was successful, cognitoUserSession will contain tokens for the user } @Override public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) { // The API needs user sign-in credentials to continue AuthenticationDetails authenticationDetails = new AuthenticationDetails(userId, password, null); // Pass the user sign-in credentials to the continuation authenticationContinuation.setAuthenticationDetails(authenticationDetails); // Allow the sign-in to continue authenticationContinuation.continueTask(); } @Override public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) { // Multi-factor authentication is required; get the verification code from user multiFactorAuthenticationContinuation.setMfaCode(mfaVerificationCode); // Allow the sign-in process to continue multiFactorAuthenticationContinuation.continueTask(); } @Override public void onFailure(Exception exception) { // Sign-in failed, check exception for the cause } }; // Sign in the user cognitoUser.getSessionInBackground(authenticationHandler);

Step 7: Getting User Details

After authenticating a user, you can retrieve other information about the user in the user pool, as shown in the following example.

Copy
// Implement callback handler for getting details GetDetailsHandler getDetailsHandler = new GetDetailsHandler() { @Override public void onSuccess(CognitoUserDetails cognitoUserDetails) { // The user detail are in cognitoUserDetails } @Override public void onFailure(Exception exception) { // Fetch user details failed, check exception for the cause } }; // Fetch the user details cognitoUser.getDetailsInBackground(getDetailsHandler);

Step 8: Getting Credentials to Access AWS Resources for an App User

To get credentials to access AWS resources for your user, first create an identity pool and associate your user pool with that identity pool.

To get AWS credentials to access AWS resources

  1. Sign in to the Amazon Cognito console.

  2. Choose Manage Federated Identities.

  3. Choose Create new identity pool. Type a name for your identity pool in Identity pool name.

  4. Expand the Authentication providers section. On the Cognito tab, type the User Pool ID and the App Client ID for the user pool you just created.

  5. Choose Create Pool.

  6. In your application code, add the ID tokens, received after successful authentication, to your credentials provider, as follows.

    Copy
    // Get id token from CognitoUserSession. String idToken = cognitoUserSession.getIdToken().getJWTToken(); // Create a credentials provider, or use the existing provider. CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(context, IDENTITY_POOL_ID, REGION); // Set up as a credentials provider. Map<String, String> logins = new HashMap<String, String>(); logins.put("cognito-idp.us-east-1.amazonaws.com/us-east-1_123456678", cognitoUserSession.getIdToken().getJWTToken()); credentialsProvider.setLogins(logins);
  7. Use the credentials provider to access AWS resources, such as a Amazon DynamoDB table, as follows.

    Copy
    AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);

Step 9: Setting IAM Permissions to Enable Access to AWS Resources

When you create an identity pool, Amazon Cognito creates two IAM roles: Cognito<identity pool name>Auth_Role and Cognito<identity pool name>Unauth_Role. By default, these roles only allow access to Amazon Cognito Identity and Amazon Cognito Sync. To allow your application to access AWS services such as Amazon DynamoDB, you must attach the appropriate managed policy to the role. For example, if your application needs to read and write to a DynamoDB database you must attach the AmazonDynamoDBFullAccess managed policy to the role, as described in the following procedure.

To set IAM permissions to enable access to AWS resources

  1. Sign in to the AWS Management Console and open the IAM console at https://console.aws.amazon.com/iam/.

  2. Choose the authenticated role for your policy from the list of roles, and then choose Attach Policy.

  3. Choose the required policy for the list of managed policies (AmazonDynamoDBFullAccess, for example), and then choose Attach Policy.

You application can now perform create, read, update, and delete operations in DynamoDB.