Using Cognito, Angular and Node.js together (3/3)

Application configuration

Objective: Configure a Node.js service using Express.js to authenticate Cognito tokens.

As prerequisites, we are one npm package, so please install the one listed below:

  • cognito-express [1]: Cognito-express authenticates API requests by verifying the Json Web Tokens signatures generated by Amazon Cognito.

Configure application back-end

To secure the back-end application, we need to setup a middle-ware method that will be applied to all routings where it's needed and a configuration file that returns variables depending on the environment.

The configuration file will return 3 variables, the user pool identifier, the application client identifier and the region where those 2 resources are located in AWS. The code for it looks like this:

module.exports = (function (env) {
    switch (env) {
        case 'prod':
            return {
                userPoolId: 'us-east-2_XYZXYZXYS',
                clientId: 'ABCDEFGHIJKLMNOPQ123',
                region: 'us-east-2'
            };
        case 'uat':
            return {
                userPoolId: 'us-east-2_XYZXYZXYS',
                clientId: 'ABCDEFGHIJKLMNOPQ123',
                region: 'us-east-2'
            };
        default:
            return {
                userPoolId: 'us-east-2_XYZXYZXYS',
                clientId: 'ABCDEFGHIJKLMNOPQ123',
                region: 'us-east-2'
            };
    }
})(process.env.NODE_ENV);

The middle-ware method uses the configuration file and the cognito-express package installed before. This method will be executed in all routings to validate that the token provided is valid according to Cognito. In case the Cognito User Pool can't validate the token, this middle-ware method will return a 401 status code for the request. The code for this method looks like this:

const CognitoExpress = require("cognito-express");
const awsConfig = require('../helpers/awsConfig');

const cognitoExpress = new CognitoExpress({
    region: awsConfig.region,
    cognitoUserPoolId: awsConfig.userPoolId,
    tokenUse: "id",
    tokenExpiration: 3600000
});

function validateAdmin(req, res, next) {
    let accessTokenFromClient = req.headers.authorization;
 
    if (!accessTokenFromClient) return res.status(401).send("Access Token missing from header");

    cognitoExpress.validate(accessTokenFromClient, function (err, response) {
        if (err) return res.status(401).send(err);
        res.locals.user = response;
        next();
    });
}

module.exports = validateAdmin;

Finally, we will apply to the routings the middle-ware method using the "use" method from the ExpressJS router.

var express = require('express');
var router = express.Router();
var cognitoValidator = require('../helpers/cognitoValidator');

var dynamo = require('../helpers/dataService');
router.use(cognitoValidator);

router.get('/'
    , function (req, res) {
        dynamo.getData().then(data => {
            res.json(data);
        }).catch(err => {
            console.log(err);
            res.sendStatus(500);
        });
    });

module.exports = router;

Summary

After finishing all 3 parts of this tutorial, you should have completed the configuration to use Cognito in an Angular application with a Node.js backend service.