<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Om Choudhary</title>
    <description>The latest articles on DEV Community by Om Choudhary (@0mchoudhary).</description>
    <link>https://dev.to/0mchoudhary</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2906354%2F63d7f73a-308e-4567-ba2c-305d7d840d60.png</url>
      <title>DEV Community: Om Choudhary</title>
      <link>https://dev.to/0mchoudhary</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/0mchoudhary"/>
    <language>en</language>
    <item>
      <title>Serverless User Authentication with AWS Cognito &amp; DynamoDB.</title>
      <dc:creator>Om Choudhary</dc:creator>
      <pubDate>Sun, 02 Mar 2025 06:19:48 +0000</pubDate>
      <link>https://dev.to/0mchoudhary/serverless-user-authentication-with-aws-cognito-dynamodb-m19</link>
      <guid>https://dev.to/0mchoudhary/serverless-user-authentication-with-aws-cognito-dynamodb-m19</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffttsma3oobtvwjvaqlo8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffttsma3oobtvwjvaqlo8.png" alt="Image description" width="800" height="497"&gt;&lt;/a&gt;🚀 &lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;User authentication is a critical part of web and mobile applications. Instead of managing authentication manually, AWS provides Cognito, which allows seamless user sign-up, login, and token-based authentication.&lt;/p&gt;

&lt;p&gt;In this tutorial, we’ll build a fully serverless authentication system using:&lt;br&gt;
✅ &lt;strong&gt;AWS Lambda&lt;/strong&gt; - Serverless compute for API functions&lt;br&gt;
✅ &lt;strong&gt;Amazon API&lt;/strong&gt; Gateway - Expose API endpoints&lt;br&gt;
✅ &lt;strong&gt;AWS Cognito&lt;/strong&gt; - User authentication and authorization&lt;br&gt;
✅ &lt;strong&gt;DynamoDB&lt;/strong&gt; - Store user data&lt;br&gt;
✅ &lt;strong&gt;Serverless Framework&lt;/strong&gt; - Automate deployment&lt;/p&gt;

&lt;p&gt;By the end of this tutorial, you’ll have a working authentication system with &lt;strong&gt;JWT authentication, CRUD operations, and secure API access&lt;/strong&gt;. 🔐&lt;/p&gt;

&lt;p&gt;🌍 &lt;strong&gt;Project Overview&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;🔹 &lt;strong&gt;Features&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;✔ User Sign-up &amp;amp; Login using AWS Cognito&lt;br&gt;
✔ JWT Authentication for API security&lt;br&gt;
✔ User Data Management (CRUD) with DynamoDB&lt;br&gt;
✔ Serverless API Deployment with AWS Lambda &amp;amp; API Gateway&lt;br&gt;
✔ Secure IAM Roles for fine-grained access control&lt;/p&gt;

&lt;p&gt;🏗 &lt;strong&gt;Architecture Diagram&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;User ➝ API Gateway ➝ AWS Lambda ➝ Cognito &amp;amp; DynamoDB ➝ Response&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;⚙️ &lt;strong&gt;Step 1: Setting Up the Serverless Project&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, install the Serverless Framework:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g serverless
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, create a new project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;serverless create --template aws-nodejs --path serverless-auth
cd serverless-auth
npm init -y
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Install dependencies:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install express serverless-http @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb @aws-sdk/client-cognito-identity-provider jsonwebtoken dotenv
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🛠 &lt;strong&gt;Step 2: Define API in&lt;/strong&gt; &lt;code&gt;serverless.yml&lt;/code&gt;&lt;br&gt;
Create &lt;code&gt;serverless.yml&lt;/code&gt; with the following configuration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;service: serverless-auth

plugins:
  - serverless-dotenv-plugin

provider:
  name: aws
  runtime: nodejs18.x
  region: us-east-1
  environment:
    USERS_TABLE: UsersTable
    COGNITO_USER_POOL_ID: your-user-pool-id
    COGNITO_CLIENT_ID: your-client-id
    COGNITO_CLIENT_SECRET: your-client-secret
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:PutItem
        - dynamodb:GetItem
        - dynamodb:Scan
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:us-east-1:*:table/UsersTable"

functions:
  registerUser:
    handler: handler.handler
    events:
      - http:
          path: register
          method: post
          cors: true
      - http:
          path: users/{userId}
          method: get
          cors: true
      - http:
          path: users
          method: get
          cors: true
      - http:
          path: users/{userId}
          method: put
          cors: true
      - http:
          path: users/{userId}
          method: delete
          cors: true

  loginUser:
    handler: handler.handler
    events:
      - http:
          path: login
          method: post
          cors: true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🔑 &lt;strong&gt;Step 3: Implement the Authentication API&lt;/strong&gt;&lt;br&gt;
Create an &lt;code&gt;app.js&lt;/code&gt; file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { CognitoIdentityProviderClient, SignUpCommand, InitiateAuthCommand } = require("@aws-sdk/client-cognito-identity-provider");
const { DynamoDBDocumentClient, GetCommand, PutCommand, DeleteCommand, ScanCommand } = require("@aws-sdk/lib-dynamodb");
const express = require("express");
const jwt = require("jsonwebtoken");
const crypto = require("crypto");

const app = express();
const cognito = new CognitoIdentityProviderClient({ region: "us-east-1" });
const USERS_TABLE = process.env.USERS_TABLE;
const client = new DynamoDBClient({ region: process.env.AWS_REGION });
const docClient = DynamoDBDocumentClient.from(client);

app.use(express.json());

// JWT Authentication Middleware
const authenticate = (req, res, next) =&amp;gt; {
  const token = req.headers.authorization?.split(" ")[1];
  if (!token) return res.status(401).json({ error: "Unauthorized - No token provided" });

  try {
    const decoded = jwt.verify(token, process.env.COGNITO_PUBLIC_KEY);
    req.user = decoded;
    next();
  } catch (err) {
    return res.status(401).json({ error: "Invalid token", details: err.message });
  }
};

// Login Route
app.post("/login", async (req, res) =&amp;gt; {
  const { email, password } = req.body;
  const params = {
    AuthFlow: "USER_PASSWORD_AUTH",
    ClientId: process.env.COGNITO_CLIENT_ID,
    AuthParameters: {
      USERNAME: email,
      PASSWORD: password,
    },
  };

  try {
    const response = await cognito.send(new InitiateAuthCommand(params));
    res.json({ token: response.AuthenticationResult.IdToken });
  } catch (error) {
    res.status(400).json({ error: "Could not authenticate user", details: error.message });
  }
});

module.exports = app;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🚀 &lt;strong&gt;Step 4: Deploy &amp;amp; Test the API&lt;/strong&gt;&lt;br&gt;
Run the deployment command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;serverless deploy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use Postman or cURL to test the API:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -X POST https://your-api-url/dev/login -H "Content-Type: application/json" -d '{ "email": "test@example.com", "password": "YourPass123" }'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🎯 &lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In this guide, we built and deployed a serverless authentication system using AWS services. This architecture ensures scalability, cost efficiency, and security. 💡&lt;/p&gt;

&lt;p&gt;🔹 Want to enhance this further? Add OAuth2 (Google/Facebook Login) or Multi-Factor Authentication (MFA) for stronger security! 🔒&lt;/p&gt;

&lt;p&gt;Let me know if you found this useful! Drop your thoughts in the comments below. 🚀&lt;/p&gt;

</description>
      <category>aws</category>
      <category>serverless</category>
      <category>node</category>
      <category>authentication</category>
    </item>
  </channel>
</rss>
