Setting up an AWS Cognito User Pool and building a React login component
Setting Up AWS Cognito User Pool
- Log in to AWS Management Console and navigate to the Amazon Cognito service.
- Click on "Create a User Pool".
- Provide a name for your user pool.
- Configure Sign-in Options. Choose Username as the primary method of user identification. Optionally, allow email and/or phone numbers as aliases.
- Configure Password Policy. Define the minimum length and strength (e.g., uppercase, numbers, special characters).
- Enable Multi-Factor Authentication (MFA) if needed.
- Choose User Attributes like email or phone number to store additional user information.
Configure App Clients
- 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.
- Under Authentication Flows, ensure "Enable username-password authentication (USER_PASSWORD_AUTH)" is checked.
- 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)
- In Cognito, go to Federated Identities → Create Identity Pool.
- Check Enable access to unauthenticated and authenticated identities.
- Link it to the Cognito User Pool (select your User Pool and App Client ID).
- Click Create Pool and configure the IAM roles generated for authenticated users.
- 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;
Comments
Post a Comment