AWS Cognito User Pool Example: A Step-by-Step Guide

Amazon Cognito simplifies user authentication and authorization for mobile and web applications. By using a Cognito User Pool, you can securely manage user registration, login, and account recovery, while integrating with third-party identity providers. In this article, we’ll walk through a practical example of setting up and using an AWS Cognito User Pool to authenticate users.


What Is AWS Cognito?

Amazon Cognito is a managed service for user identity and access management. It provides:

  • User Pools: Handle user registration, login, and account management.
  • Federated Identities: Enable access via third-party identity providers (e.g., Google, Facebook).

AWS Cognito User Pool Example

Objective

We’ll set up an AWS Cognito User Pool to:

  1. Allow user registration and login.
  2. Securely authenticate users using a web application.
  3. Provide JWT tokens for API requests.

Step 1: Create a Cognito User Pool

  1. Navigate to the AWS Cognito Console:
    • Go to Manage User PoolsCreate a User Pool.
  2. Configure the User Pool:
    • Pool Name: example-user-pool.
    • Sign-In Options: Select Email as the preferred sign-in method.
  3. Set Password Policy:
    • Configure password strength and complexity requirements.
  4. User Registration:
    • Enable email as a required attribute.
    • Enable user self-registration.
  5. MFA and Verification:
    • Enable Multi-Factor Authentication (MFA) if needed.
    • Choose email for account verification.
  6. App Clients:
    • Create an App Client without a secret (e.g., example-client).
    • Enable username and password-based authentication.
  7. Complete the setup and save the User Pool.

Step 2: Integrate the User Pool with Your Application

Install AWS Amplify

If you're building a web or mobile application, AWS Amplify simplifies Cognito integration:

npm install aws-amplify @aws-amplify/ui-react

Configure Amplify

Create a src/aws-exports.js file to hold your Cognito configuration:

const awsConfig = {
  Auth: {
    region: "your-region",
    userPoolId: "your-user-pool-id",
    userPoolWebClientId: "your-app-client-id",
  },
};

export default awsConfig;

Update your application’s entry file:

import Amplify from "aws-amplify";
import awsConfig from "./aws-exports";

Amplify.configure(awsConfig);

Step 3: Implement User Authentication

User Registration

import { Auth } from "aws-amplify";

async function signUp(username, password, email) {
  try {
    const response = await Auth.signUp({
      username,
      password,
      attributes: {
        email,
      },
    });
    console.log("Sign-up successful:", response);
  } catch (error) {
    console.error("Error signing up:", error);
  }
}

User Login

async function signIn(username, password) {
  try {
    const response = await Auth.signIn(username, password);
    console.log("Sign-in successful:", response);
  } catch (error) {
    console.error("Error signing in:", error);
  }
}

Fetch Current User

async function getCurrentUser() {
  try {
    const user = await Auth.currentAuthenticatedUser();
    console.log("Current user:", user);
  } catch (error) {
    console.error("Error fetching current user:", error);
  }
}

Step 4: Test the User Pool

  1. Register a User:
    • Call the signUp function with a test username, password, and email.
  2. Verify Email:
    • Retrieve the verification code from the email and complete the registration.
  3. Sign In:
    • Call the signIn function with the username and password.
  4. Fetch Tokens:
    • After logging in, retrieve the user's ID token for secure API access.

Step 5: Secure API Requests

Use the JWT token provided by Cognito to authenticate API requests. Example using Axios:

import axios from "axios";
import { Auth } from "aws-amplify";

async function makeSecureRequest() {
  const user = await Auth.currentAuthenticatedUser();
  const token = user.signInUserSession.idToken.jwtToken;

  const response = await axios.get("https://your-api-endpoint", {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });

  console.log("API Response:", response.data);
}

Best Practices for AWS Cognito

  1. Enable MFA: Enhance security by requiring multi-factor authentication.
  2. Use Groups: Organize users into groups for role-based access control.
  3. Monitor Logs: Use CloudWatch to track authentication activity.
  4. Integrate with Identity Providers: Expand authentication options with Google, Facebook, or SAML providers.

Conclusion

AWS Cognito User Pools provide a robust, scalable solution for managing user authentication. By following this example, you can create a user pool, integrate it into your application, and securely authenticate users. AWS Cognito simplifies the process of adding authentication to modern applications, letting developers focus on building features rather than managing identity infrastructure.