Cognito - Javascript Identity Sdk (amazon-cognito-identity-js)
About
The Cognito Javascript Sdk is one of the Cognito Sdk
and has been moved and wrapped in the amplify library. See below
The Amazon Cognito Identity SDK for JavaScript has been moved and wrapped into the auth amplify library
Git Location:
- Before: aws/amazon-cognito-identity-js.
Amazon Cognito offers two user pool SDKs:
- 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.
- Cognito - Js Auth Sdk - A wrapper around the idendity sdk that webpages to your app for the following: sign-up, sign-in, confirmation, multi-factor authentication (MFA), and sign-out see.
This page is about the Amazon Cognito Identity SDK>
Articles Related
Prerequisites
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:
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);
}
});
Object Creation
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
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);
Operations
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);
- Sign Up with the userPool object
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());
});
Users Confirmation
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);
});
Resend a Confirmation Code
to a user_object
cognitoUser.resendConfirmationCode(function(err, result) {
if (err) {
alert(err);
return;
}
alert(result);
});
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.
Sign-in
Cognito - Sign-in within the identity library.
Prerequisites:
- The user must be confirmed to obtain a session.
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);
- Sign the user in with a user object
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)
}
});
Attribute
Cognito - User Attribute (User Directory)
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());
});
}
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);
});
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);
});
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);
}
});
Session
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();
});
}
get a session for current User and refresh credentials
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!');
}
});
Password
Changing Password
for an authenticated user
cognitoUser.changePassword('oldPassword', 'newPassword', function(err, result) {
if (err) {
alert(err);
return;
}
console.log('call result: ' + result);
});
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);
}
});
Mfa
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);
});
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);
});
Sign out
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();
}
Sign out globally
signs the current user out globally by invalidating all issued tokens.
cognitoUser.globalSignOut();
Delete a User
deletes an authenticated user
cognitoUser.deleteUser(function(err, result) {
if (err) {
alert(err);
return;
}
console.log('call result: ' + result);
});
Example
App
- Example of utilisation in the serverless web app.
- https://github.com/aws-samples/aws-mobile-react-sample - React Starter kit
Snippet
Documentation / Reference
- For more information about the SDK, see the amazon-cognito-identity-js project page on GitHub.