Menu
Amazon Cognito
Developer Guide (Version Last Updated: 07/28/2016)

Tutorial: Integrating User Pools for JavaScript Apps

This tutorial helps you use the Amazon Cognito SDK for JavaScript to get started with user pools.

Step 1: Creating a User Pool for your JavaScript 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 user pool ID and an app client ID. 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. Ensure that the Generate client secret check box is cleared, and then choose Set attribute read and write permissions. Select the attributes that require write permissions. Required attributes always have write permissions.

    Note

    The Amazon Cognito JavaScript SDK does not use the app client secret. If you configure your user pool app client with an app client secret, the SDK will throw exceptions.

  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 and client ID. You can find the app client ID under Apps on the left navigation bar.

Step 2: Creating a User Pool Object in Your App

To create a user pool object, you need the user pool ID and client ID that you obtained in step 1. The following example shows how to create a CognitoUserPool object. The JavaScript SDK does not support the app client secret. If you configure your user pool app client with an app client secret, the SDK will throw exceptions.

Copy
AWSCognito.config.region = 'us-east-1'; var poolData = { UserPoolId : '...', // your user pool id here ClientId : '...' // your app client id here }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); var userData = { Username : '...', // your username here Pool : userPool };

Step 3: Signing up Users for Your App

After creating a user pool object, users can be signed up for the app. The user's information can be collected through the web UI and used to populate CognitoUserAttribute objects that are passed in the signUp call.

Copy
var attributeList = []; var dataEmail = { Name : 'email', Value : '...' // your email here }; var dataPhoneNumber = { Name : 'phone_number', Value : '...' // your phone number here with +country code and no delimiters in front }; var attributeEmail = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail); var attributePhoneNumber = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataPhoneNumber); attributeList.push(attributeEmail); attributeList.push(attributePhoneNumber); var cognitoUser; userPool.signUp('username', 'password', attributeList, null, function(err, result){ if (err) { alert(err); return; } cognitoUser = result.user; console.log('user name is ' + cognitoUser.getUsername()); });

Step 4: Confirming Users for Your App

After signing up, the user confirms the sign-up by entering a code sent either through SMS or email (based on the user pool settings). Alternatively, you can use a PreSignUp AWS Lambda function to automatically confirm your users. To confirm sign-up, you must collect the code ('123456' in the following example) received by the user and use it as follows.

Copy
cognitoUser.confirmRegistration('123456', true, function(err, result) { if (err) { alert(err); return; } console.log('call result: ' + result); });

The registration code can be resent by using the resendConfirmationCode method of a cognitoUser object. This is an unauthenticated call and only the username, the client ID, and the user pool information are needed.

Step 5: Signing Users in to Your App

A confirmed user signs in to obtain a session. The session contains an ID token that contains user claims, an access token that is used internally to perform authenticated calls, and a refresh token that is used internally to refresh the session after it expires each hour. For more information about tokens, see Using Tokens with User Pools. If sign in is successful, the onSuccess callback is called. If sign in fails, the onFailure callback is called. If sign in requires MFA, the mfaRequired callback is called and you must invoke sendMFACode on the cognitoUser object. The verification code that is received must be passed and the user is then signed in.

Copy
var authenticationData = { Username : '...', // your username here Password : '...', // your password here }; var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData); var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData); cognitoUser.authenticateUser(authenticationDetails, { onSuccess: function (result) { console.log('access token + ' + result.getAccessToken().getJwtToken()); }, onFailure: function(err) { alert(err); }, mfaRequired: function(codeDeliveryDetails) { var verificationCode = prompt('Please input verification code' ,''); cognitoUser.sendMFACode(verificationCode, this); } });

Step 6: Getting User Details

After signing in, a user can perform authorized operations such as retrieving user attributes, verifying user attributes (such as an unverified email address), deleting user attributes, updating user attributes, changing the user password, and deleting the user account. For user pools that have an optional MFA setting, users can enable or disable MFA for themselves. Signing out from the app clears the local user session and the user must sign in again to establish a new session.

If users forget their passwords, they can initiate a forgotten password flow. A code will be sent to the user. The user uses this code together with a new password to complete the flow. The relevant call is forgotPassword on a cognitoUser object that is unauthenticated; the relevant callbacks are shown in the following example.

Copy
cognitoUser.forgotPassword({ onSuccess: function (result) { console.log('call result: ' + result); }, onFailure: function(err) { alert(err); }, inputVerificationCode() { var verificationCode = prompt('Please input verification code ' ,''); var newPassword = prompt('Enter new password ' ,''); cognitoUser.confirmPassword(verificationCode, newPassword, this); } });

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

If you want to work with other AWS services, you must first create an Amazon Cognito identity pool. After you create this identity pool, you can get AWS credentials by passing the identity pool ID and the ID token (which were obtained earlier) when signing in the user. The following example shows how to populate IdentityPoolId and pass the ID token through the Logins map.

Copy
AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'us-east-1:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', Logins: { 'cognito-idp.us-east-1.amazonaws.com/us-east-1_XXXXXXXXX': result.getIdToken().getJwtToken() } }); AWS.config.credentials.get(function(err){ if (err) { alert(err); } });

Next Steps

For more examples and an overview of the code used in this tutorial, see the Amazon Cognito Identity JavaScript GitHub repository.