Authentication Simplified with AWS Cognito

It took a while for me to find info on how to practically implement web application authentication. Turns out it is really simple to do with AWS Cognito. What Cognito does is authenticates to a pool of (email or SMS confirmed) users and sends back a JWT (Javascript Web Token) once authenticated.

This post will function as an “essential” guide to Cognito. I’ll include the least amount of code as possible for authentication to occur in a web application with just an email address and password. You could find more detailed info at this AWS tutorial (The tutorial is what the following code is vanilla-fied from.).

First off download and include the AWS SDK and NPM SDK in an HTML page.

Then log into AWS Cognito and create a user pool. Use the defaults. Check: “Also allow sign in with verified email address”. Add an app client. Uncheck: “Generate client secret”. Start up your JS and include relevant fields.

_Cognito = {
    cognito: {
        userPoolId: '',// e.g. us-west-2_abcde3fghij
        userPoolClientId: '', // e.g. 12abcde3fgh4ijklmn5
        region: '' // e.g. us-west-2
    }
};

var Cognito = {};

var poolData = {
    UserPoolId: _Cognito.cognito.userPoolId,
    ClientId: _Cognito.cognito.userPoolClientId
};

var userPool; 

userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

Now the SDK is available to use. Let’s register a user.

function register(email, password, onSuccess, onFailure) {
    var dataEmail = {
        Name: 'email',
        Value: email
    };
    var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);

    userPool.signUp(email, password, [attributeEmail], null,
        function signUpCallback(err, result) {
            if (!err) {
                onSuccess(result);
            } else {
                onFailure(err);
            }
        }
    );
}

 if (document.readyState == 'loading'){
   document.addEventListener("DOMContentLoaded", function(){ 
     document.querySelector('#registrationForm').addEventListener('submit', handleRegister); 
   });
}

function handleRegister(event) {
    var email = document.querySelector('#emailInputRegister').value;
    var password = document.querySelector('#passwordInputRegister').value;

    var onSuccess = function registerSuccess(result) {
        var cognitoUser = result.user;
        console.log('user name is ' + cognitoUser.getUsername());
        var confirmation = ('Registration successful. Please check your email inbox or spam folder for your verification code.');
        if (confirmation) {
            //Go to verification page;
        }
    };
    var onFailure = function registerFailure(err) {
        alert(err);
    };
    event.preventDefault(); 
    register(email, password, onSuccess, onFailure); 
}

An email will be sent to the user that includes a verification code. With that you’ll verify the user.

function verify(email, code, onSuccess, onFailure) {
    createCognitoUser(email).confirmRegistration(code, true, function confirmCallback(err, result) {
        if (!err) {
            onSuccess(result);
        } else {
            onFailure(err);
        }
    });
}

if (document.readyState == 'loading'){
   document.addEventListener("DOMContentLoaded", function(){ 
     document.querySelector('#verifyForm').addEventListener('submit', handleVerify);
   });
}

function handleVerify(event) {
    var email = document.querySelector('#emailInputVerify').value;
    var code = document.querySelector('#codeInputVerify').value;
    event.preventDefault();
    verify(email, code,
        function verifySuccess(result) {
            console.log('call result: ' + result);
            console.log('Successfully verified');
            alert('Verification successful.');
        },
        function verifyError(err) {
            alert(err);
        }
    );
}

To sign in:

if (document.readyState == 'loading'){
   document.addEventListener("DOMContentLoaded", function(){
     document.querySelector('#signinForm').addEventListener('submit', handleSignin); 
   });

}

function signin(email, password, onSuccess, onFailure) {
    var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails({
        Username: email,
        Password: password
    });

    var cognitoUser = createCognitoUser(email);
    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: onSuccess,
        onFailure: onFailure
    });
}

function handleSignin(event) {
    var email = document.querySelector('#emailInputSignin').value;
    var password = document.querySelector('#passwordInputSignin').value;
    event.preventDefault();
    signin(email, password,
        function signinSuccess() {
            console.log('Successfully Logged In'); 
        },
        function signinError(err) {
            alert(err);
        }
    );
}

Here we will get the token. You could see what the token consists of at JWT.io.

let user = userPool.getCurrentUser();

if (user){
    user.getSession(function sessionCallback(err, session){
        if (err) {
           //Nada session info.
        } else {
           //JWT
           console.log(session.getIdToken().getJwtToken());
        }
});
}

To sign out:

Cognito.signOut = function signOut() {
    userPool.getCurrentUser().signOut();
};

if (document.readyState == 'loading'){
      document.addEventListener("DOMContentLoaded", function(){ 
        document.querySelector('#signOut').addEventListener('click', function() {
            Cognito.signOut();
            alert("You have been signed out.");
          })
        })
      }

That’s the gist of authentication with Cognito. I’ve included a working example.

Leave a comment

Your email address will not be published. Required fields are marked *