Lädt...

🔧 Serverless User Authentication with AWS Cognito & DynamoDB.


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

Image description🚀 Introduction

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.

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

By the end of this tutorial, you’ll have a working authentication system with JWT authentication, CRUD operations, and secure API access. 🔐

🌍 Project Overview

🔹 Features

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

🏗 Architecture Diagram
User ➝ API Gateway ➝ AWS Lambda ➝ Cognito & DynamoDB ➝ Response

⚙️ Step 1: Setting Up the Serverless Project

First, install the Serverless Framework:

npm install -g serverless

Then, create a new project:

serverless create --template aws-nodejs --path serverless-auth
cd serverless-auth
npm init -y

Install dependencies:

npm install express serverless-http @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb @aws-sdk/client-cognito-identity-provider jsonwebtoken dotenv

🛠 Step 2: Define API in serverless.yml
Create serverless.yml with the following configuration:

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

🔑 Step 3: Implement the Authentication API
Create an app.js file

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) => {
  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) => {
  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;

🚀 Step 4: Deploy & Test the API
Run the deployment command:

serverless deploy

Use Postman or cURL to test the API:

curl -X POST https://your-api-url/dev/login -H "Content-Type: application/json" -d '{ "email": "[email protected]", "password": "YourPass123" }'

🎯 Conclusion

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

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

Let me know if you found this useful! Drop your thoughts in the comments below. 🚀

...

🔧 Serverless User Authentication with AWS Cognito & DynamoDB.


📈 59.08 Punkte
🔧 Programmierung

🔧 Cognito Inception: How to add Cognito as OIDC Identity Provider in Cognito


📈 53.5 Punkte
🔧 Programmierung

🔧 AWS Serverless CRUD App Tutorial Using Lambda, API Gateway, DynamoDB, Cognito and Cloudfront CDN


📈 47.42 Punkte
🔧 Programmierung

🔧 Learn serverless on AWS - Authentication with Cognito


📈 37.8 Punkte
🔧 Programmierung

🕵️ Vectra Cognito Brain/Cognito Sensor up to 4.2 Management Console privilege escalation


📈 35.67 Punkte
🕵️ Sicherheitslücken

🕵️ Vectra Cognito Brain/Cognito Sensor up to 4.2 CouchDB Code Execution


📈 35.67 Punkte
🕵️ Sicherheitslücken

🕵️ Vectra Cognito Brain/Cognito Sensor up to 4.1 Web Management Console cross site scripting


📈 35.67 Punkte
🕵️ Sicherheitslücken

🔧 Building Serverless APIS with Serverless,Node.js, Typescript, DynamoDB, and Lambda.


📈 34.25 Punkte
🔧 Programmierung

🔧 Building Serverless APIS with Serverless,Node.js, Typescript, DynamoDB, and Lambda.


📈 34.25 Punkte
🔧 Programmierung

🔧 No Hassle: Serverless Social Login Powered by AWS Cognito


📈 32.92 Punkte
🔧 Programmierung

🔧 Part 1 : Serverless project with CDK, AWS Lambda@Edge, Cognito and Amplify


📈 32.92 Punkte
🔧 Programmierung

🔧 Building a Secure Serverless Angular App with AWS CDK, Cognito, Lambda, and API Gateway


📈 32.92 Punkte
🔧 Programmierung

🔧 Understanding AWS Cognito: A Complete Guide to User Authentication and Management


📈 32.81 Punkte
🔧 Programmierung

🔧 AWS Cognito for User Authentication: A Comprehensive Guide


📈 32.81 Punkte
🔧 Programmierung

🔧 Pentesting AWS Cognito: User Authentication Risks


📈 32.81 Punkte
🔧 Programmierung

🔧 Adding Cognito Authentication to our Serverless Dash App


📈 32.59 Punkte
🔧 Programmierung

🔧 [Mini Project] Serverless URL Shortener Using AWS Lambda, Api Gateway and DynamoDB


📈 29.59 Punkte
🔧 Programmierung

🔧 Building Serverless Applications with AWS Lambda and integrating with DynamoDB


📈 29.59 Punkte
🔧 Programmierung

🔧 What I Learned from the 'Amazon DynamoDB for Serverless Architectures' Course on AWS Skill Builder


📈 29.59 Punkte
🔧 Programmierung

🔧 "Building a Serverless REST API with AWS Lambda, API Gateway, and DynamoDB Using Python"


📈 29.59 Punkte
🔧 Programmierung

🔧 Create a Fast Node.js Serverless Backend Using AWS Lambda and DynamoDB


📈 29.59 Punkte
🔧 Programmierung

🔧 Learn serverless on AWS step-by-step: Master DynamoDB!


📈 29.59 Punkte
🔧 Programmierung

🔧 Query DynamoDB with SQL using Athena - Leveraging DynamoDB Exports to S3 (1/2)


📈 29 Punkte
🔧 Programmierung

🔧 [20 Days of DynamoDB] Day 17 - DynamoDB BatchGetItem operation


📈 29 Punkte
🔧 Programmierung

🔧 [20 Days of DynamoDB] Day 5 - Avoid overwrites when using DynamoDB UpdateItem API


📈 29 Punkte
🔧 Programmierung

🔧 DynamoDB Transactions: An E-Commerce with Amazon DynamoDB


📈 29 Punkte
🔧 Programmierung

🔧 DynamoDB Basic - Part 1: Introduction DynamoDB


📈 29 Punkte
🔧 Programmierung

🔧 Hosting a Custom Login and Registration UI with AWS Amplify and AWS Cognito


📈 28.25 Punkte
🔧 Programmierung

🔧 Effortless User Management with AWS Cognito


📈 27.94 Punkte
🔧 Programmierung

matomo