Amazon Cognito
Developer Guide

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.

var poolData = { UserPoolId : 'us-east-1_TcoKGbf7n', ClientId : '4pe2usejqcdmhi0a25jp4b5sh3' }; var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData); var attributeList = []; var dataEmail = { Name : 'email', Value : 'email@mydomain.com' }; var dataPhoneNumber = { Name : 'phone_number', Value : '+15555555555' }; var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail); var attributePhoneNumber = new AmazonCognitoIdentity.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

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

Retrieve the current user from local storage

var data = { UserPoolId : 'us-east-1_Iqc12345', ClientId : '12345du353sm7khjj1q' }; var userPool = new AmazonCognitoIdentity.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.

Note

If the user was created by the administrator in the console, and not through the preceding JavaScript examples, see Example: Handling Users Created Using the AdminCreateUser API in the Mobile SDK for Android and Creating User Accounts as Administrator.

var authenticationData = { Username : 'username', Password : 'password', }; var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData); var poolData = { UserPoolId : 'us-east-1_TcoKGbf7n', ClientId : '4pe2usejqcdmhi0a25jp4b5sh3' }; var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData); var userData = { Username : 'username', Pool : userPool }; var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData); cognitoUser.authenticateUser(authenticationDetails, { onSuccess: function (result) { var accessToken = result.getAccessToken().getJwtToken(); /* Use the idToken for Logins Map when Federating User Pools with identity pools or when passing through an Authorization Header to an API Gateway Authorizer*/ var 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.

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.

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

Create a User Pool Object

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

Sign Up For the Application

var attribute = { Name : 'email', Value : 'email@mydomain.com' }; var attributeEmail = new AmazonCognitoIdentity.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

var userData = { Username : 'username', Pool : userPool }; cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData); var authenticationData = { Username : 'username', Password : 'password', }; var authenticationDetails = new AmazonCognitoIdentity.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.

var attributeList = []; var attribute = { Name : 'nickname', Value : 'joe' }; var attribute = new AmazonCognitoIdentity.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.

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.

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.

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.

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

Confirm Registration

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.

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.

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.

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.

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

Sign a User Out Globally

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

cognitoUser.globalSignOut();

Get the Current User

The following example retrieves the current user from local storage.

var data = { UserPoolId : '...', // Your user pool id here ClientId : '...' // Your client id here }; var userPool = new AmazonCognitoIdentity.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.

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.

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.

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.

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.

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.

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.

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

Select the MFA Method and Authenticate Using TOTP MFA

The following example selects the MFA method and authenticates using TOTP.

var authenticationData = { Username : 'username', Password : 'password', }; var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData); var poolData = { UserPoolId : '...', // Your user pool id here ClientId : '...' // Your client id here }; var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData); var userData = { Username : 'username', Pool : userPool }; var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData); cognitoUser.authenticateUser(authenticationDetails, { onSuccess: function (result) { var accessToken + ' + result.getAccessToken().getJwtToken()); }, onFailure: function(err) { alert(err); }, mfaSetup: function(challengeName, challengeParameters) { cognitoUser.associateSoftwareToken(this); }, associateSecretCode : function(secretCode) { var challengeAnswer = prompt('Please input the TOTP code.' ,''); cognitoUser.verifySoftwareToken(challengeAnswer, 'My TOTP device', this); }, selectMFAType : function(challengeName, challengeParameters) { var mfaType = prompt('Please select the MFA method.', ''); cognitoUser.sendMFASelectionAnswer(mfaType, this); }, totpRequired : function(secretCode) { var challengeAnswer = prompt('Please input the TOTP code.' ,''); cognitoUser.sendMFACode(challengeAnswer, this, 'SOFTWARE_TOKEN_MFA'); } });

Enable and Set SMS MFA as the Preferred MFA Method for the User

The following example enables and sets SMS MFA as the preferred MFA method for the user.

smsMfaSettings = { PreferredMfa : true, Enabled : true }; cognitoUser.setUserMfaPreference(smsMfaSettings, null, function(err, result) { if (err) { alert(err); } console.log('call result ' + result) });

Enable and Set TOTP Software Token MFA as the Preferred MFA Method for the User

The following example enables and sets TOTP software token MFA as the preferred MFA method for the user.

totpMfaSettings = { PreferredMfa : true, Enabled : true }; cognitoUser.setUserMfaPreference(null, totpMfaSettings, function(err, result) { if (err) { alert(err); } console.log('call result ' + result) });