All Projects → ghdna → Cognito Express

ghdna / Cognito Express

Licence: mit
Authenticates API requests on a Node application by verifying the JWT signature of AccessToken or IDToken generated by Amazon Cognito.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Cognito Express

Aws Serverless Auth Reference App
Serverless reference app and backend API, showcasing authentication and authorization patterns using Amazon Cognito, Amazon API Gateway, AWS Lambda, and AWS IAM.
Stars: ✭ 724 (+338.79%)
Mutual labels:  aws, aws-cognito, authentication, cognito, amazon-cognito
Amplify Js
A declarative JavaScript library for application development using cloud services.
Stars: ✭ 8,539 (+5075.15%)
Mutual labels:  aws, aws-cognito, cognito, amazon-cognito
Cognito Backup Restore
AIO Tool for backing up and restoring AWS Cognito User Pools
Stars: ✭ 142 (-13.94%)
Mutual labels:  aws, aws-cognito, cognito, amazon-cognito
Aws Amplify Vue
A Vue.js starter app integrated with AWS Amplify
Stars: ✭ 359 (+117.58%)
Mutual labels:  aws, cognito, amazon-cognito
aws-sdk-net-extensions-cognito
An extension library to assist in the Amazon Cognito User Pools authentication process
Stars: ✭ 80 (-51.52%)
Mutual labels:  amazon, aws-cognito, amazon-cognito
aws-amplify-react-custom-ui
Building a Custom UI Authentication For AWS Amplify
Stars: ✭ 21 (-87.27%)
Mutual labels:  cognito, aws-cognito, amazon-cognito
Cloudfront Auth
An AWS CloudFront [email protected] function to authenticate requests using Google Apps, Microsoft, Auth0, OKTA, and GitHub login
Stars: ✭ 471 (+185.45%)
Mutual labels:  aws, authentication, jwt
Naperg
Fullstack Boilerplate GraphQL. Made with React & Prisma + authentication & roles
Stars: ✭ 661 (+300.61%)
Mutual labels:  expressjs, authentication, jwt
Aws Cognito Angular Quickstart
An Angular(v5)-based QuickStart single-page app utilizing Amazon Cognito, S3, and DynamoDB (Serverless architecture)
Stars: ✭ 685 (+315.15%)
Mutual labels:  aws, cognito, amazon-cognito
Amazon Cognito Identity Js
Amazon Cognito Identity SDK for JavaScript
Stars: ✭ 965 (+484.85%)
Mutual labels:  aws, aws-cognito, amazon-cognito
Aws Sdk Perl
A community AWS SDK for Perl Programmers
Stars: ✭ 153 (-7.27%)
Mutual labels:  aws, amazon-web-services, amazon
Terraform Aws Cognito Auth
Serverless Authentication as a Service (AaaS) provider built on top of AWS Cognito
Stars: ✭ 248 (+50.3%)
Mutual labels:  aws, authentication, cognito
Cognitocurl
🦉🤖Easily sign curl calls to API Gateway with Cognito authorization token.
Stars: ✭ 76 (-53.94%)
Mutual labels:  aws, amazon-web-services, cognito
Serverless Photo Recognition
A collection of 3 lambda functions that are invoked by Amazon S3 or Amazon API Gateway to analyze uploaded images with Amazon Rekognition and save picture labels to ElasticSearch (written in Kotlin)
Stars: ✭ 345 (+109.09%)
Mutual labels:  aws, jwt, amazon-cognito
Workshop Donkeytracker
Workshop to build a serverless tracking application for your mobile device with an AWS backend
Stars: ✭ 27 (-83.64%)
Mutual labels:  aws, amazon-web-services, cognito
Ixortalk.aws.cognito.jwt.security.filter
Spring Boot security filter for decoding Cognito JWT IdTokens
Stars: ✭ 75 (-54.55%)
Mutual labels:  aws, jwt, cognito
Express Jwt
An example API for creating/verifying json web tokens
Stars: ✭ 105 (-36.36%)
Mutual labels:  expressjs, authentication, jwt
Serverless Dynamodb Autoscaling
Serverless Plugin for Amazon DynamoDB Auto Scaling configuration.
Stars: ✭ 142 (-13.94%)
Mutual labels:  aws, amazon
Security.identity
.NET DevPack Identity is a set of common implementations to help you implementing Identity, Jwt, claims validation and another facilities
Stars: ✭ 165 (+0%)
Mutual labels:  authentication, jwt
Autospotting
Saves up to 90% of AWS EC2 costs by automating the use of spot instances on existing AutoScaling groups. Installs in minutes using CloudFormation or Terraform. Convenient to deploy at scale using StackSets. Uses tagging to avoid launch configuration changes. Automated spot termination handling. Reliable fallback to on-demand instances.
Stars: ✭ 2,014 (+1120.61%)
Mutual labels:  aws, amazon-web-services

Cognito-Express: API Authentication with AWS Congito

NPM

Build Status Package Quality Code Climate Coverage Status dependencies Status Downloads

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

Architecture

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

  1. Download and store the JSON Web Token (JWT) set for your user pool.
  2. Decode the token string into JWT format.
  3. Check the iss claim. It should match your user pool.
  4. Check the tokenUse claim. It should match your set preference for access or id token types
  5. Get the kid from the JWT token header and retrieve the corresponding JSON Web Key that was stored in step 1.
  6. Verify the signature of the decoded JWT token.
  7. 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:

  1. By adding them explicitly in Request Headers
  2. Just save the tokens as cookies. This way they get attached to request headers whenever APIs are invoked. (recommended)

Configuration

//Initializing CognitoExpress constructor
const cognitoExpress = new CognitoExpress({
	region: "us-east-1",
	cognitoUserPoolId: "us-east-1_dXlFef73t",
	tokenUse: "access", //Possible Values: access | id
	tokenExpiration: 3600000 //Up to default expiration of 1 hour (3600000 ms)
});

Usage

cognitoExpress.validate(accessTokenFromClient, function(err, response) {
	if (err) {
		/*
			//API is not authenticated, do something with the error.
		    //Perhaps redirect user back to the login page
			
			//ERROR TYPES:
			
			//If accessTokenFromClient is null or undefined
			err = {
			    "name": "TokenNotFound",
			    "message": "access token not found"
			}
			
			//If tokenuse doesn't match accessTokenFromClient
			{
			    "name": "InvalidTokenUse",
			    "message": "Not an id token"
			}

			//If token expired
			err = {
			    "name": "TokenExpiredError",
			    "message": "jwt expired",
			    "expiredAt": "2017-07-05T16:41:59.000Z"
			}

			//If token's user pool doesn't match the one defined in constructor
			{
			    "name": "InvalidUserPool",
			    "message": "access token is not from the defined user pool"
			}

		*/
	} else {
		//Else API has been authenticated. Proceed.
		res.locals.user = response; //Optional - if you want to capture user information
		next();
	}
});


Full Example

app.js - server
//app.js
"use strict";

const express = require("express"),
	CognitoExpress = require("cognito-express"),
	port = process.env.PORT || 8000;

const app = express(),
	authenticatedRoute = express.Router(); //I prefer creating a separate Router for authenticated requests

app.use("/api", authenticatedRoute);

//Initializing CognitoExpress constructor
const cognitoExpress = new CognitoExpress({
	region: "us-east-1",
	cognitoUserPoolId: "us-east-1_dXlFef73t",
	tokenUse: "access", //Possible Values: access | id
	tokenExpiration: 3600000 //Up to default expiration of 1 hour (3600000 ms)
});

//Our middleware that authenticates all APIs under our 'authenticatedRoute' Router
authenticatedRoute.use(function(req, res, next) {
	
	//I'm passing in the access token in header under key accessToken
	let accessTokenFromClient = req.headers.accesstoken;

	//Fail if token not present in header. 
	if (!accessTokenFromClient) return res.status(401).send("Access Token missing from header");

	cognitoExpress.validate(accessTokenFromClient, function(err, response) {
		
		//If API is not authenticated, Return 401 with error message. 
		if (err) return res.status(401).send(err);
		
		//Else API has been authenticated. Proceed.
		res.locals.user = response;
		next();
	});
});


//Define your routes that need authentication check
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
//client.js - angular example

"use strict";

//I stored my access token value returned from Cognito in a cookie called ClientAccessToken

app.controller("MyFirstAPI", function($scope, $http, $cookies) {
	$http({
		method: "GET",
		url: "/api/myfirstapi",
		headers: {
			accesstoken: $cookies.get("ClientAccessToken") 
            }
		}
	}).then(
		function success(response) {
			//Authenticated. Do something with the response. 
		},
		function error(err) {
			console.error(err);
		}
	);
});

Contributors

Gary Arora

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].