Cognito-Express: API Authentication with AWS Congito
Synopsis
cognito-express authenticates API requests on a Node.js application (either running on a server or in an AWS Lambda function) by verifying the JWT signature of AccessToken
or IDToken
generated by Amazon Cognito.
Motivation
This module lets you authenticate Node.js API requests by verifying the JWT signature of AccessToken
or IDToken
- without needing to call Amazon Cognito for each API invocation.
The module can be easily and unobtrusively integrated into any application or framework that supports Connect-style middleware, including Express.
This module essentially bundles steps 1-7 listed on the official AWS documentation on Using ID Tokens and Access Tokens in your Web APIs
- Download and store the JSON Web Token (JWT) set for your user pool.
- Decode the token string into JWT format.
- Check the
iss
claim. It should match your user pool. - Check the
tokenUse
claim. It should match your set preference for access
or id
token types - Get the kid from the JWT token header and retrieve the corresponding JSON Web Key that was stored in step 1.
- Verify the signature of the decoded JWT token.
- Check the exp claim and make sure the token is not expired.
You can now trust the claims inside the token and use it as it fits your requirements.
Prerequisites
After successful authentication of a user, Amazon Cognito issues three tokens to the client:
- ID token
- Access token
- Refresh token
(Note: The login mechanism is not covered by this module and you'll have to build that separately)
Save these tokens within the client app (preferably as cookies).
When any API is invoked from client, pass in the AccessToken
or IDToken
to the server.
It's completely up to you how you pass in the AccessToken
or IDToken
. Here are two options:
- By adding them explicitly in Request Headers
- Just save the tokens as cookies. This way they get attached to request headers whenever APIs are invoked. (recommended)
Configuration
const cognitoExpress = new CognitoExpress({
region: "us-east-1",
cognitoUserPoolId: "us-east-1_dXlFef73t",
tokenUse: "access",
tokenExpiration: 3600000
});
Usage
cognitoExpress.validate(accessTokenFromClient, function(err, response) {
if (err) {
} else {
res.locals.user = response;
next();
}
});
Full Example
app.js - server
"use strict";
const express = require("express"),
CognitoExpress = require("cognito-express"),
port = process.env.PORT || 8000;
const app = express(),
authenticatedRoute = express.Router();
app.use("/api", authenticatedRoute);
const cognitoExpress = new CognitoExpress({
region: "us-east-1",
cognitoUserPoolId: "us-east-1_dXlFef73t",
tokenUse: "access",
tokenExpiration: 3600000
});
authenticatedRoute.use(function(req, res, next) {
let accessTokenFromClient = req.headers.accesstoken;
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();
});
});
authenticatedRoute.get("/myfirstapi", function(req, res, next) {
res.send(`Hi ${res.locals.user.username}, your API call is authenticated!`);
});
app.listen(port, function() {
console.log(`Live on port: ${port}!`);
});
client.js - angular example
"use strict";
app.controller("MyFirstAPI", function($scope, $http, $cookies) {
$http({
method: "GET",
url: "/api/myfirstapi",
headers: {
accesstoken: $cookies.get("ClientAccessToken")
}
}
}).then(
function success(response) {
},
function error(err) {
console.error(err);
}
);
});
Contributors
Gary Arora
License
MIT