Now that you have created a user pool and a client to access the pool, let’s see how you use Amazon Cognito in your application.
In the application/ directory of your project, there is a file called auth.js. This file contains a few authentication helpers for your application. There are four core functions to that file. Let’s review them in turn.
The first function is createCognitoUser and is used when registering a new user in Amazon Cognito. The function looks as follows:
const createCognitoUser = async (username, password, email, phoneNumber) => {
const signUpParams = {
ClientId: process.env.COGNITO_CLIENT_ID,
Username: username,
Password: password,
UserAttributes: [
{
Name: 'email',
Value: email
},
{
Name: 'phone_number',
Value: phoneNumber
}
]
}
await cognitoidentityserviceprovider.signUp(signUpParams).promise()
const confirmParams = {
UserPoolId: process.env.USER_POOL_ID,
Username: username
}
await cognitoidentityserviceprovider.adminConfirmSignUp(confirmParams).promise()
return {
username,
email,
phoneNumber
}
}
It uses the Amazon Cognito client ID that you set in the previous step, as well as the username, password, email, and phone number given by the user, to create a new user. Additionally, you immediately confirm the user so that the user can sign in. Usually, you opt for a confirmation process that verified the user’s email and/or mobile phone number so that you have a contact method for them. That’s out of scope for this tutorial, so you can just automatically confirm new users.
The second core method is the login function that is used when registered users are authenticating. The code is as shown below:
const login = async (username, password) => {
const params = {
ClientId: process.env.COGNITO_CLIENT_ID,
UserPoolId: process.env.USER_POOL_ID,
AuthFlow: 'ADMIN_NO_SRP_AUTH',
AuthParameters: {
USERNAME: username,
PASSWORD: password
}
}
const { AuthenticationResult: { IdToken: idToken } }= await cognitoidentityserviceprovider.adminInitiateAuth(params).promise()
return idToken
}
Like in the createCognitoUser function, you use the Client Id and the given parameters to make a call to Amazon Cognito. The adminInitiateAuth method for Amazon Cognito authenticates the user and return tokens if the authentication method passes. You use ID tokens for authentication, so that is what you return for successful user logins.
The third function is fetchUserByUsername. You use this function to fetch a user object by a given username to find the phone number for a user you need to notify. The code is as follows:
const fetchUserByUsername = async username => {
const params = {
UserPoolId: process.env.USER_POOL_ID,
Username: username
};
const user = await cognitoidentityserviceprovider.adminGetUser(params).promise();
const phoneNumber = user.UserAttributes.filter(attribute => attribute.Name === "phone_number")[0].Value;
return {
username,
phoneNumber
};
};
The function takes a single parameter, username. It then calls the adminGetUser function from the Amazon Cognito client. Then, it filters through the attributes to find the user’s phone number and returns an object with the user’s username and phone number.
Finally, there is a verifyToken function. The contents of this function are as follows:
const verifyToken = async (idToken) => {
function getKey(header, callback){
client.getSigningKey(header.kid, function(err, key) {
var signingKey = key.publicKey || key.rsaPublicKey;
callback(null, signingKey);
});
}
return new Promise((res, rej) => {
jwt.verify(idToken, getKey, {}, function(err, decoded) {
if (err) { rej(err) }
res(decoded)
})
})
}
This function verifies an ID token that has been passed up with a request. The ID token given by Amazon Cognito is a JSON Web Token, and the verifyToken function confirms that the token was signed by your trusted source and to identify the user. This function is used in endpoints that require authentication to ensure that the requesting user has access.
In subsequent modules, you use these four authentication functions in your backend application.