├── .gitignore ├── .env-sample ├── README.md ├── index.js ├── routes └── AuthRoutes.js ├── package.json ├── .vscode └── launch.json ├── controllers └── AuthController.js ├── cognito-services └── index.js └── helpers └── AwsConfig.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .env -------------------------------------------------------------------------------- /.env-sample: -------------------------------------------------------------------------------- 1 | APP_PORT=3010 2 | 3 | AWS_COGNITO_USER_POOL_ID= 4 | AWS_COGNITO_CLIENT_ID= 5 | AWS_COGNITO_REGION= 6 | AWS_COGNITO_IDENTITY_POOL_ID= -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Node.js API Express using AWS Cognito for authentication 2 | 3 | ## Routes 4 | 5 | ``` 6 | /api/signup 7 | ``` 8 | ``` 9 | /api/verify 10 | ``` 11 | ``` 12 | /api/signin 13 | ``` 14 | 15 | ## How to run 16 | 17 | ``` 18 | node index.js 19 | ``` 20 | 21 | 22 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const AuthRouter = require('./routes/AuthRoutes') 3 | const app = express(); 4 | 5 | app.use(express.json()); 6 | app.use('/api', AuthRouter); 7 | 8 | app.listen(process.env.PORT, () => { 9 | console.log(`Running on ${process.env.PORT}`); 10 | }); 11 | 12 | module.exports = app; -------------------------------------------------------------------------------- /routes/AuthRoutes.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const authController = require('../controllers/AuthController'); 3 | 4 | const router = express.Router(); 5 | 6 | router.get('/signup', authController.SignUp); 7 | router.get('/signin', authController.SignIn); 8 | router.get('/verify', authController.Verify); 9 | 10 | module.exports = router; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cognito", 3 | "description": "cognito", 4 | "version": "8.10.0", 5 | "scripts": { 6 | "start": "node index.js" 7 | }, 8 | "dependencies": { 9 | "amazon-cognito-identity-js": "^4.4.0", 10 | "async": "^3.2.0", 11 | "aws-sdk": "^2.751.0", 12 | "dotenv": "8.2.0", 13 | "express": "^4.18.1", 14 | "jwt-decode": "^2.2.0", 15 | "node-fetch": "^2.6.1", 16 | "uuid": "^8.3.0" 17 | }, 18 | "devDependencies": { 19 | "serverless-plugin-warmup": "^4.9.0" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "pwa-node", 9 | "request": "launch", 10 | "name": "Launch Program", 11 | "skipFiles": [ 12 | "/**" 13 | ], 14 | "program": "${filename}" 15 | } 16 | ] 17 | } -------------------------------------------------------------------------------- /controllers/AuthController.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | require('dotenv').config(); 3 | const Cognito = require('../cognito-services'); 4 | 5 | async function SignUp(req, res) { 6 | const response = await Cognito.signUp(req.body.email,req.body.password); 7 | res.json(response) 8 | } 9 | 10 | async function Verify(req, res) { 11 | const response = await Cognito.verify(req.body.email,req.body.codeEmailVerify); 12 | res.json(response) 13 | } 14 | 15 | async function SignIn(req, res) { 16 | const response = await Cognito.signIn(req.body.email,req.body.password); 17 | res.json(response) 18 | } 19 | 20 | module.exports = { 21 | SignIn, Verify, SignUp 22 | } 23 | -------------------------------------------------------------------------------- /cognito-services/index.js: -------------------------------------------------------------------------------- 1 | const AwsConfig = require('../helpers/AwsConfig'); 2 | 3 | function signUp(email, password, agent = 'none') { 4 | return new Promise((resolve) => { 5 | AwsConfig.initAWS(); 6 | AwsConfig.setCognitoAttributeList(email,agent); 7 | AwsConfig.getUserPool().signUp(email, password, AwsConfig.getCognitoAttributeList(), null, function(err, result){ 8 | if (err) { 9 | return resolve({ statusCode: 422, response: err }); 10 | } 11 | const response = { 12 | username: result.user.username, 13 | userConfirmed: result.userConfirmed, 14 | userAgent: result.user.client.userAgent, 15 | } 16 | return resolve({ statusCode: 201, response: response }); 17 | }); 18 | }); 19 | } 20 | 21 | function verify(email, code) { 22 | return new Promise((resolve) => { 23 | AwsConfig.getCognitoUser(email).confirmRegistration(code, true, (err, result) => { 24 | if (err) { 25 | return resolve({ statusCode: 422, response: err }); 26 | } 27 | return resolve({ statusCode: 400, response: result }); 28 | }); 29 | }); 30 | } 31 | 32 | function signIn(email, password) { 33 | return new Promise((resolve) => { 34 | AwsConfig.getCognitoUser(email).authenticateUser(AwsConfig.getAuthDetails(email, password), { 35 | onSuccess: (result) => { 36 | const token = { 37 | accessToken: result.getAccessToken().getJwtToken(), 38 | idToken: result.getIdToken().getJwtToken(), 39 | refreshToken: result.getRefreshToken().getToken(), 40 | } 41 | return resolve({ statusCode: 200, response: AwsConfig.decodeJWTToken(token) }); 42 | }, 43 | 44 | onFailure: (err) => { 45 | return resolve({ statusCode: 400, response: err.message || JSON.stringify(err)}); 46 | }, 47 | }); 48 | }); 49 | } 50 | 51 | module.exports = { 52 | signUp, 53 | verify, 54 | signIn 55 | } -------------------------------------------------------------------------------- /helpers/AwsConfig.js: -------------------------------------------------------------------------------- 1 | const AWS = require('aws-sdk'); 2 | const jwt_decode = require('jwt-decode'); 3 | const AmazonCognitoIdentity = require('amazon-cognito-identity-js'); 4 | let cognitoAttributeList = []; 5 | 6 | const poolData = { 7 | UserPoolId : process.env.AWS_COGNITO_USER_POOL_ID, 8 | ClientId : process.env.AWS_COGNITO_CLIENT_ID 9 | }; 10 | 11 | const attributes = (key, value) => { 12 | return { 13 | Name : key, 14 | Value : value 15 | } 16 | }; 17 | 18 | function setCognitoAttributeList(email, agent) { 19 | let attributeList = []; 20 | attributeList.push(attributes('email',email)); 21 | attributeList.forEach(element => { 22 | cognitoAttributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute(element)); 23 | }); 24 | } 25 | 26 | function getCognitoAttributeList() { 27 | return cognitoAttributeList; 28 | } 29 | 30 | function getCognitoUser(email) { 31 | const userData = { 32 | Username: email, 33 | Pool: getUserPool() 34 | }; 35 | return new AmazonCognitoIdentity.CognitoUser(userData); 36 | } 37 | 38 | function getUserPool(){ 39 | return new AmazonCognitoIdentity.CognitoUserPool(poolData); 40 | } 41 | 42 | function getAuthDetails(email, password) { 43 | var authenticationData = { 44 | Username: email, 45 | Password: password, 46 | }; 47 | return new AmazonCognitoIdentity.AuthenticationDetails(authenticationData); 48 | } 49 | 50 | function initAWS (region = process.env.AWS_COGNITO_REGION, identityPoolId = process.env.AWS_COGNITO_IDENTITY_POOL_ID) { 51 | AWS.config.region = region; 52 | AWS.config.credentials = new AWS.CognitoIdentityCredentials({ 53 | IdentityPoolId: identityPoolId, 54 | }); 55 | } 56 | 57 | function decodeJWTToken(token) { 58 | const { email, exp, auth_time , token_use, sub} = jwt_decode(token.idToken); 59 | return { token, email, exp, uid: sub, auth_time, token_use }; 60 | } 61 | 62 | module.exports = { 63 | initAWS, 64 | getCognitoAttributeList, 65 | getUserPool, 66 | getCognitoUser, 67 | setCognitoAttributeList, 68 | getAuthDetails, 69 | decodeJWTToken, 70 | } 71 | --------------------------------------------------------------------------------