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:
Amazon Cognito offers two user pool SDKs:
This page is about the Amazon Cognito Identity SDK>
The Amazon Cognito Identity SDK for JavaScript requires two configuration values from your AWS Account in order to access your Cognito User Pool:
See:
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);
}
});
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
You create a user object with a user_pool
var userData = {
Username : '...', // your username here
Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
// 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());
});
Users validation can happen by:
Example where 123456 is the validation code.
cognitoUser.confirmRegistration('123456', true, function(err, result) {
if (err) {
alert(err);
return;
}
console.log('call result: ' + result);
});
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.
Cognito - Sign-in within the identity library.
Prerequisites:
If sign in:
Code:
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)
}
});
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());
});
}
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);
});
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);
});
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);
}
});
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();
});
}
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!');
}
});
for an authenticated user
cognitoUser.changePassword('oldPassword', 'newPassword', function(err, result) {
if (err) {
alert(err);
return;
}
console.log('call result: ' + result);
});
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);
}
});
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);
});
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);
});
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();
}
signs the current user out globally by invalidating all issued tokens.
cognitoUser.globalSignOut();
deletes an authenticated user
cognitoUser.deleteUser(function(err, result) {
if (err) {
alert(err);
return;
}
console.log('call result: ' + result);
});