All Articles

Implementing AWS Cognito Authentication with Amplify: A Complete Guide

AWS Amplify combined with Amazon Cognito provides a robust authentication solution for web applications. In this guide, we’ll walk through setting up Cognito User Pools, integrating it with Amplify, and implementing sign-up and sign-in functionality.

Prerequisites

  • AWS Account with appropriate permissions
  • Node.js and npm installed
  • Basic understanding of React (we’ll use it for our example)

Creating a Cognito User Pool

  1. Navigate to Cognito Console

    • Log into AWS Console
    • Search for “Cognito” in the services search bar
    • Click “Create user pool”
  2. Configure Sign-in Experience

    • Select “Email” as the primary authentication
    • Under “User pool sign-in options”, choose “Email”
    • Click “Next”
  3. Configure Security Requirements

    • Password policy:
      • Minimum length: 8 characters
      • Require numbers: Yes
      • Require special characters: Yes
      • Require uppercase letters: Yes
      • Require lowercase letters: Yes
    • MFA: Optional (Choose “No MFA” for this example)
    • Click “Next”
  4. Configure Sign-up Experience

    • Self-service account recovery: Enabled
    • Required attributes:
      • Name
      • Email
    • Click “Next”
  5. Configure Message Delivery

    • Select “Send email with Cognito”
    • Click “Next”
  6. Integrate Your App

    • User pool name: “MyAppUserPool”
    • App client name: “MyAppClient”
    • Don’t generate client secret
    • Click “Next”
  7. Review and Create

    • Review all settings
    • Click “Create user pool”
    • Note down the User Pool ID and App Client ID

Setting Up Your React Application

# Create a new React application
npx create-react-app my-auth-app
cd my-auth-app

# Install Amplify dependencies
npm install aws-amplify @aws-amplify/ui-react

Configuring Amplify

Create a new file src/aws-config.js:

import { Amplify } from 'aws-amplify';

Amplify.configure({
  Auth: {
    region: 'us-east-1', // Replace with your region
    userPoolId: 'us-east-1_xxxxxx', // Replace with your User Pool ID
    userPoolWebClientId: 'xxxxxxxxxxxxxx', // Replace with your App Client ID
  }
});

Implementing Authentication UI

Update your src/App.js:

import React from 'react';
import { Authenticator } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';

function App() {
  return (
    <Authenticator>
      {({ signOut, user }) => (
        <div>
          <h1>Welcome {user.attributes.email}</h1>
          <button onClick={signOut}>Sign out</button>
        </div>
      )}
    </Authenticator>
  );
}

export default App;

Customizing the Authentication Flow

You can customize the sign-up and sign-in experience by adding custom components:

import { Authenticator } from '@aws-amplify/ui-react';

const components = {
  Header() {
    return (
      <div>
        <h1>My Application</h1>
      </div>
    );
  },
  Footer() {
    return (
      <div>
        <p>© 2024 My Company</p>
      </div>
    );
  }
};

function App() {
  return (
    <Authenticator components={components}>
      {({ signOut, user }) => (
        // Your authenticated app content
      )}
    </Authenticator>
  );
}

Testing the Authentication Flow

  1. Sign Up Flow

    • Launch your application
    • Click “Create Account”
    • Enter email and password
    • Verify email through the verification code
    • Complete additional required attributes
  2. Sign In Flow

    • Enter registered email
    • Enter password
    • Access protected content

Security Considerations

  1. Password Policies

    • Ensure strong password requirements are maintained
    • Consider implementing MFA for production environments
  2. Token Handling

    • Amplify handles JWT tokens automatically
    • Tokens are securely stored in browser storage
    • Refresh tokens are managed automatically
  3. API Protection

    • Use Cognito tokens for API Gateway authentication
    • Implement proper CORS policies

Common Issues and Troubleshooting

  1. Invalid Client ID

    • Double-check the App Client ID in your configuration
    • Ensure the App Client settings match your requirements
  2. Email Verification Issues

    • Check if SES is properly configured
    • Verify email templates are correct
  3. CORS Errors

    • Add your domain to the App Client’s allowed origins
    • Check browser console for specific CORS errors

Conclusion

AWS Amplify with Cognito provides a secure and scalable authentication solution. This setup gives you:

  • User registration and authentication
  • Password recovery
  • Email verification
  • JWT token handling
  • Customizable UI components

Remember to update security settings and implement additional features like MFA before moving to production.

Next Steps

  • Implement social sign-in providers
  • Add custom authentication challenges
  • Set up user groups and roles
  • Implement advanced security features

By following this guide, you’ve created a fully functional authentication system using AWS Amplify and Cognito. The solution is production-ready and can be extended based on your specific requirements.

Published Nov 10, 2024

Welcome to Vians Tech