Cognito - Javascript Identity Sdk (in the browser)

> AWS (Amazon Web Services) > Aws - Cognito

1 - About

How to use the Cognito Javascript SDK.

The Amazon Cognito Identity SDK for JavaScript is now part of the AWS Amplify Library.

Amazon Cognito offers two user pool SDKs, this page is about the Amazon Cognito Identity SDK>. It's the core user pools library that enable to interact with the user management and authentication functions in the Amazon Cognito User Pools API.

for the auth sdk, that add webpages to your app for the following: sign-up, sign-in, confirmation, multi-factor authentication (MFA), and sign-out see Cognito - Js Auth Sdk

Advertising

3 - Prerequisites

3.1 - Creates a user pool ID and an app client ID

The Amazon Cognito Identity SDK for JavaScript requires two configuration values from your AWS Account in order to access your Cognito User Pool:

  • The User Pool Id, e.g. us-east-1_aB12cDe34
  • A User Pool App Client Id, e.g. 7ghr5379orhbo88d52vphda6s9

See:

3.2 - Creates a Cognito identity pool

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.

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

4 - Object Creation

4.1 - User Pool Object

var poolData = {
    UserPoolId : '...', // your user pool id here
    ClientId : '...' // your app client id here
};
// Create the User Pool Object
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

How to get the app client id and user pool id, See user pool and app id creation

Advertising

4.2 - User Object

You create a user object with a user pool

var userData = {
    Username : '...', // your username here
    Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);

5 - Operations

5.1 - Sign-Up

  • user attributes
// A Email attribute 
var dataEmail = {
    Name : 'email',
    Value : '...' // your email here
};
var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);
 
// A phone number attribute
var dataPhoneNumber = {
    Name : 'phone_number',
    Value : '...' // your phone number here with +country code and no delimiters in front
};
var attributePhoneNumber = new AmazonCognitoIdentity.CognitoUserAttribute(dataPhoneNumber);
 
// An array of attribute
var attributeList = []; 
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());
});

5.2 - Users Confirmation

5.2.1 - Validation

Users validation can happen by:

  • the user entering a code sent either through SMS or email (based on the user pool settings)
  • a PreSignUp AWS Lambda function to automatically confirm users.

Example where 123456 is the validation code.

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

5.2.2 - Resend a Confirmation Code

to a user object

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

5.2.3 - Email

The verification email may end up in your spam folder. For real deployments, configure the user pool to use Amazon Simple Email Service to send emails from a domain you own.

5.3 - Sign-in

Aws Cognito - Sign-in within the identity library.

Prerequisites:

If sign in:

  • is successful, the onSuccess callback is called.
  • fails, the onFailure callback is called.
  • 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.

Code:

  • Creating the auth properties
var authenticationData = {
        Username : '...', // your username here
        Password : '...', // your password here
    };
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
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);
	},
	mfaRequired: function(codeDeliveryDetails) {
		var verificationCode = prompt('Please input verification code' ,'');
		cognitoUser.sendMFACode(verificationCode, this);
	},
        newPasswordRequired: function(userAttributes, requiredAttributes) {
            // User was signed up by an admin and must provide new 
            // password and required attributes, if any, to complete 
            // authentication.
 
            // userAttributes: object, which is the user's current profile. It will list all attributes that are associated with the user. 
            // Required attributes according to schema, which don’t have any values yet, will have blank values.
            // requiredAttributes: list of attributes that must be set by the user along with new password to complete the sign-in.
 
 
            // Get these details and call 
            // newPassword: password that user has given
            // attributesData: object with key as attribute name and value that the user has given.
            cognitoUser.completeNewPasswordChallenge(newPassword, attributesData, this)
        }
});

5.4 - Attribute

5.4.1 - Retrieving user attributes

Retrieve the current user from local storage from a user pool object (after signing in?)

var cognitoUser = userPool.getCurrentUser();
if (cognitoUser != null) {
	cognitoUser.getSession(function(err, session) {
		if (err) {
			alert(err);
			return;
		}
		console.log('session validity: ' + session.isValid());
	});
}

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

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

5.4.4 - Verify an Attribute (for instance email)

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

5.5 - Session

5.5.1 - Get the current user, session and identity pool

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

5.5.2 - get a session for current User and refresh credentials

Cognito - Session

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

5.6 - Password

5.6.1 - Changing Password

for an authenticated user

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

5.6.2 - Forgotten Password

In 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.

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

5.7 - Mfa

5.7.1 - Disable MFA for a User Pool

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

5.7.2 - Enable MFA

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

5.8 - Sign out

5.8.1 - sign out from the application

Signing out from the app clears the local user session and the user must sign in again to establish a new session.

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

5.8.2 - Sign out globally

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

cognitoUser.globalSignOut();

5.9 - Delete a User

deletes an authenticated user

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

6 - Example

6.1 - App

6.2 - Snippet

7 - Documentation / Reference

aws/cognito/js_identity.txt · Last modified: 2019/04/22 16:53 by gerardnico