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

Examples: Using the JavaScript SDK

Register a User with the Application

You need to create a CognitoUserPool object by providing a UserPoolId and a ClientId, and registering by using a username, password, attribute list, and validation data.

Copy
AWSCognito.config.region = 'us-east-1'; //This is required to derive the endpoint var poolData = { UserPoolId : 'us-east-1_TcoKGbf7n', ClientId : '4pe2usejqcdmhi0a25jp4b5sh3' }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); var attributeList = []; var dataEmail = { Name : 'email', Value : 'email@mydomain.com' }; var dataPhoneNumber = { Name : 'phone_number', Value : '+15555555555' }; var attributeEmail = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail); var attributePhoneNumber = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataPhoneNumber); attributeList.push(attributeEmail); attributeList.push(attributePhoneNumber); userPool.signUp('username', 'password', attributeList, null, function(err, result){ if (err) { alert(err); return; } cognitoUser = result.user; console.log('user name is ' + cognitoUser.getUsername()); });

Delete an Authenticated User

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

Retrieve the current user from local storage

Copy
var data = { UserPoolId : 'us-east-1_Iqc12345', ClientId : '12345du353sm7khjj1q' }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); var cognitoUser = userPool.getCurrentUser(); if (cognitoUser != null) { cognitoUser.getSession(function(err, session) { if (err) { alert(err); return; } console.log('session validity: ' + session.isValid()); }); }

Authenticate a User

The following example authenticates a user and establishes a user session with the Amazon Cognito service.

Copy
var authenticationData = { Username : 'username', Password : 'password', }; var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData); var poolData = { UserPoolId : 'us-east-1_TcoKGbf7n', ClientId : '4pe2usejqcdmhi0a25jp4b5sh3' }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); var userData = { Username : 'username', Pool : userPool }; var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData); cognitoUser.authenticateUser(authenticationDetails, { onSuccess: function (result) { console.log('access token + ' + result.getAccessToken().getJwtToken()); /*Use the idToken for Logins Map when Federating User Pools with Cognito Identity or when passing through an Authorization Header to an API Gateway Authorizer*/ console.log('idToken + ' + result.idToken.jwtToken); }, onFailure: function(err) { alert(err); }, });

Enable MFA for a User Pool

The following example enables multi-factor authentication (MFA) for a user pool that has an optional MFA setting for an authenticated user.

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

Disable MFA for a User Pool

The following example disables multi-factor authentication (MFA) for a user pool that has an optional MFA setting for an authenticated user.

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

Create a User Pool Object

Copy
var data = { UserPoolId : 'us-east-1_q2Y6U8uuY', ClientId : '224kjog47ojnt9ov773erj7qn9' }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data);

Sign Up For the Application

Copy
var attribute = { Name : 'email', Value : 'email@mydomain.com' }; var attributeEmail = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(attribute); var attributeList = []; attributeList.push(attributeEmail); var cognitoUser; userPool.signUp('username', 'password', attributeList, null, function(err, result) { if (err) { alert(err); return; } cognitoUser = result.user; });

Sign in With MFA Enabled

Copy
var userData = { Username : 'username', Pool : userPool }; cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData); var authenticationData = { Username : 'username', Password : 'password', }; var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData); cognitoUser.authenticateUser(authenticationDetails, { onSuccess: function (result) { alert('authentication successful!') }, onFailure: function(err) { alert(err); }, mfaRequired: function(codeDeliveryDetails) { var verificationCode = prompt('Please input verification code' ,''); cognitoUser.sendMFACode(verificationCode, this); } });

Update Attributes

The following example updates user attributes for an authenticated user.

Copy
var attributeList = []; var attribute = { Name : 'nickname', Value : 'joe' }; var attribute = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(attribute); attributeList.push(attribute); cognitoUser.updateAttributes(attributeList, function(err, result) { if (err) { alert(err); return; } console.log('call result: ' + result); });

Delete Attributes

The following example deletes user attributes for an authenticated user.

Copy
var attributeList = []; attributeList.push('nickname'); cognitoUser.deleteAttributes(attributeList, function(err, result) { if (err) { alert(err); return; } console.log('call result: ' + result); });

Verify an Attribute

The following example verifies user attributes for an authenticated user.

Copy
cognitoUser.getAttributeVerificationCode('email', { onSuccess: function (result) { console.log('call result: ' + result); }, onFailure: function(err) { alert(err); }, inputVerificationCode: function() { var verificationCode = prompt('Please input verification code: ' ,''); cognitoUser.verifyAttribute('email', verificationCode, this); } });

Retrieve Attributes

The following example retrieves user attributes for an authenticated user.

Copy
cognitoUser.getUserAttributes(function(err, result) { if (err) { alert(err); return; } for (i = 0; i < result.length; i++) { console.log('attribute ' + result[i].getName() + ' has value ' + result[i].getValue()); } });

Resend a Confirmation Code

The following example resends a confirmation code via SMS that confirms the registration for an unauthenticated user.

Copy
cognitoUser.resendConfirmationCode(function(err, result) { if (err) { alert(err); return; } alert(result); });

Confirm Registration

Copy
cognitoUser.confirmRegistration('123456', true, function(err, result) { if (err) { alert(err); return; } alert(result); });

Change a Password

The following example changes the current password of an authenticated user.

Copy
cognitoUser.changePassword('oldPassword', 'newPassword', function(err, result) { if (err) { alert(err); return; } console.log('call result: ' + result); });

Forgotten Password Flow

The following example starts and completes a forgotten password flow for an unauthenticated user.

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); } });

Delete a User

The following example deletes an authenticated user.

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

Sign a User Out

The following example signs the current user out from the application.

Copy
if (cognitoUser != null) { cognitoUser.signOut(); }

Sign a User Out Globally

The following example signs the current user out globally by invalidating all issued tokens.

Copy
cognitoUser.globalSignOut();

Get the Current User

The following example retrieves the current user from local storage.

Copy
var data = { UserPoolId : '...', // Your user pool id here ClientId : '...' // Your client id here }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(data); var cognitoUser = userPool.getCurrentUser(); if (cognitoUser != null) { cognitoUser.getSession(function(err, session) { if (err) { alert(err); return; } console.log('session validity: ' + session.isValid()); AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId : '...' // your identity pool id here Logins : { // Change the key below according to the specific region your user pool is in. 'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>' : session.getIdToken().getJwtToken() } }); // Instantiate aws sdk service objects now that the credentials have been updated. // example: var s3 = new AWS.S3(); }); }

Integrate a User in a User Pool with an Identity Pool

The following example integrates the current user in a user pool with the specified identity pool.

Copy
var cognitoUser = userPool.getCurrentUser(); if (cognitoUser != null) { cognitoUser.getSession(function(err, result) { if (result) { console.log('You are now logged in.'); // Add the User's Id Token to the Cognito credentials login map. AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'YOUR_IDENTITY_POOL_ID', Logins: { 'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>': result.getIdToken().getJwtToken() } }); } }); } //call refresh method in order to authenticate user and get new temp credentials AWS.config.credentials.refresh((error) => { if (error) { console.error(error); } else { console.log('Successfully logged!'); } });

List All Devices for a User

The following example lists all devices for an authenticated user. In this case, we need to pass a limit on the number of devices retrieved at a time. In the first call, the pagination token should be null. The first call returns a pagination token, which should be passed in all subsequent calls.

Copy
cognitoUser.listDevices(limit, paginationToken, { onSuccess: function (result) { console.log('call result: ' + result); }, onFailure: function(err) { alert(err); } });

List Device Information

The following example lists information about the current device.

Copy
cognitoUser.listDevices(limit, paginationToken, { onSuccess: function (result) { console.log('call result: ' + result); }, onFailure: function(err) { alert(err); } });

Remember a Device

The following example remembers a device.

Copy
cognitoUser.setDeviceStatusRemembered({ onSuccess: function (result) { console.log('call result: ' + result); }, onFailure: function(err) { alert(err); } });

Do Not Remember a Device

The following example marks a device as not to be remembered.

Copy
cognitoUser.setDeviceStatusNotRemembered({ onSuccess: function (result) { console.log('call result: ' + result); }, onFailure: function(err) { alert(err); } });

Do Not Remember a Device

The following example forgets the current device.

Copy
cognitoUser.forgetDevice({ onSuccess: function (result) { console.log('call result: ' + result); }, onFailure: function(err) { alert(err); } });

Confirm a Registered, Unauthenticated User

The following example confirms a registered, unauthenticated user using a confirmation code received via SMS message.

Copy
var poolData = { UserPoolId : 'us-east-1_TcoKGbf7n', ClientId : '4pe2usejqcdmhi0a25jp4b5sh3' }; var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData); var userData = { Username : 'username', Pool : userPool }; var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData); cognitoUser.confirmRegistration('123456', true, function(err, result) { if (err) { alert(err); return; } console.log('call result: ' + result); });