Setting up an AWS Cognito User Pool and building a React login component

Setting up an AWS Cognito User Pool and building a React login component involves several steps. After you follow this guide, you will have a React component that lets a user log into the application using AWS Cognito.

Setting Up AWS Cognito User Pool

  1. Log in to AWS Management Console and navigate to the Amazon Cognito service.
  2. Click on "Create a User Pool".
  3. Provide a name for your user pool.
  4. Configure Sign-in Options. Choose Username as the primary method of user identification. Optionally, allow email and/or phone numbers as aliases.
  5. Configure Password Policy. Define the minimum length and strength (e.g., uppercase, numbers, special characters).
  6. Enable Multi-Factor Authentication (MFA) if needed.
  7. Choose User Attributes like email or phone number to store additional user information.

Configure App Clients

  1. In the User Pool, go to the "App clients" section and create a new app client. Disable secret generation for public clients like a React app.
  2. Under Authentication Flows, ensure "Enable username-password authentication (USER_PASSWORD_AUTH)" is checked.
  3. Click Create App Client and note the App Client ID and User Pool ID for later use.

Set Up an AWS Cognito Identity Pool (For AWS Service Access)

  1. In Cognito, go to Federated Identities → Create Identity Pool.
  2. Check Enable access to unauthenticated and authenticated identities.
  3. Link it to the Cognito User Pool (select your User Pool and App Client ID).
  4. Click Create Pool and configure the IAM roles generated for authenticated users.
  5. Note the Identity Pool ID (needed for AWS service access).

Create a Login Component

If you don’t have a React project, create one:

npx create-react-app cognito-auth
cd cognito-auth
npm install @aws-sdk/client-cognito-identity-provider

Create a new file Login.js and add the following:

import React, { useState } from 'react';

import { CognitoIdentityProviderClient, InitiateAuthCommand } from '@aws-sdk/client-cognito-identity-provider';

import './Login.css'; // Import the CSS file for styling
const Login = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const handleLogin = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    const client = new CognitoIdentityProviderClient({ region: 'us-east-1' });
    const params = {
      AuthFlow: 'USER_PASSWORD_AUTH',
      ClientId: 'xxxxxxxxx2s6j8', // Replace with your Cognito App Client ID
      AuthParameters: {
        USERNAME: username,
        PASSWORD: password,
      },
    };
    try {
      const command = new InitiateAuthCommand(params);
      const response = await client.send(command);
      console.log('Login successful:', response);
      alert('Login successful!');
    } catch (err) {
      console.error('Login failed:', err);
      setError('Invalid username or password. Please try again.');
    } finally {
      setLoading(false);
    }
  };
  return (
    <div className="login-container">
      <form className="login-form" onSubmit={handleLogin}>
        <h2>Login</h2>
        {error && <div className="error-message">{error}</div>}
        <div className="form-group">
          <label htmlFor="username">Username</label>
          <input
            type="text"
            id="username"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            placeholder="Enter your username"
            required
          />
        </div>
        <div className="form-group">
          <label htmlFor="password">Password</label>
          <input
            type="password"
            id="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Enter your password"
            required
          />
        </div>
        <button type="submit" className="login-button" disabled={loading}>
          {loading ? 'Logging in...' : 'Login'}
        </button>
      </form>
    </div>
  );
};
export default Login;

Login.css

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

Comments

Popular posts from this blog

Building and Deploying a Fargate Container that runs Python and performs CloudWatch Logging

Deploying a Java web application to Amazon ECS