Leveraging Amazon Amplify for Enhanced Authentication in React Apps Advance Concepts

Tech Community • 6 min read

In our previous article, "Leveraging Amazon Amplify for Enhanced Authentication in React Apps", we explored the basics of setting up and configuring Amazon Amplify to handle authentication and authorisation in React applications. We covered how to initialise Amplify, integrate authentication, and create custom sign-up and sign-in components. 

Building on that foundation, this article delves into more advanced techniques using AWS Cognito and Amplify to further enhance your application's security and user experience.

Recap: Why Use Amazon Amplify?

As we discussed earlier, Amazon Amplify offers a seamless integration with React, making it easy to add robust authentication and user management to your applications. Its secure and developer-friendly approach simplifies the process of building scalable applications with features like multi-factor authentication, user data encryption, and pre-built UI components.

Advanced Topics in AWS Cognito and Amplify

In this continuation, we will explore advanced authentication techniques and configurations, including:

  1. Implementing Social Sign-In with AWS Cognito and Amplify
  2. Advanced Multi-Factor Authentication (MFA) Options
  3. Managing User Attributes with AWS Cognito
  4. Customising Email and SMS Messages
  5. Leveraging Cognito User Pools and Identity Pools

Each of these topics builds upon the basics covered in our initial article, providing you with the tools and knowledge to create a secure and customised user authentication experience in your React applications.

Implementing Social Sign-In with AWS Cognito and Amplify

Integrating social sign-in options enhances user experience by allowing users to log in using their existing social media accounts, such as Google, Facebook, or Amazon. AWS Amplify simplifies the process of setting up social identity providers.

Configuring Social Identity Providers

1. Set Up Providers in AWS Cognito: Navigate to the AWS Cognito console, select your user pool, and go to the "Federation" section. Add and configure social identity providers like Google, Facebook, or Amazon by providing the necessary client IDs and secrets from the respective provider's developer console.

2. Update Amplify Configuration: After setting up the providers in the Cognito console, update your Amplify configuration in your React project to include the OAuth settings for your social identity providers.

import { Amplify } from 'aws-amplify';
import awsExports from './aws-exports';

  Auth: {
    oauth: {
      domain: 'your-cognito-domain.auth.us-west-2.amazoncognito.com',
      scope: ['email', 'profile', 'openid'],
      redirectSignIn: 'http://localhost:3000/',
      redirectSignOut: 'http://localhost:3000/',
      responseType: 'code',

3. Update UI for Social Sign-In: Use Amplify’s built-in UI components or create custom buttons to trigger social sign-ins.

import { withAuthenticator } from 'aws-amplify-react';

const App = () => (
    <button onClick={() => Auth.federatedSignIn({ provider: 'Google' })}>
      Sign in with Google
    <button onClick={() => Auth.federatedSignIn({ provider: 'Facebook' })}>
      Sign in with Facebook

export default withAuthenticator(App);

Advanced Multi-Factor Authentication (MFA) Options

While basic MFA can be set up using SMS, AWS Cognito also supports advanced options like Time-based One-Time Password (TOTP) using authenticator apps.

Enabling TOTP MFA

1. Set Up TOTP in Cognito: In the AWS Cognito console, go to "MFA and verifications" and enable TOTP. Set up any necessary configurations such as the application name.

2. Integrate TOTP in Your React App: Guide users through setting up TOTP by providing a QR code for them to scan with an authenticator app and a form to enter the verification code.

import { Auth } from 'aws-amplify';
import QRCode from 'qrcode.react';

const setUpTOTP = async () => {
  const user = await Auth.currentAuthenticatedUser();
  const code = await Auth.setupTOTP(user);
  const qrCode = `otpauth://totp/MyApp:${user.username}?secret=${code}&issuer=MyApp`;
  return qrCode;

const verifyTOTP = async (code) => {
  const user = await Auth.currentAuthenticatedUser();
  await Auth.verifyTotpToken(user, code);
  await Auth.setPreferredMFA(user, 'TOTP');

// Display the QR code to the user
const qrCode = await setUpTOTP();
<QRCode value={qrCode} />;

Managing User Attributes with AWS Cognito

AWS Cognito allows you to manage and update user attributes, providing flexibility to store additional user information securely.

Updating User Attributes

1. Retrieve Current Attributes: Fetch the user's current attributes using the Amplify Auth class.

2. Update Attributes: Use the updateUserAttributes method to modify attributes like email, phone number, or custom attributes.

const updateUserAttributes = async () => {
  const user = await Auth.currentAuthenticatedUser();
  await Auth.updateUserAttributes(user, {
    email: 'new-email@example.com',
    'custom:favorite_color': 'blue',

3. Handle Attribute Updates in Your UI: Create forms to allow users to update their attributes and handle form submission to call the updateUserAttributes function.

const [email, setEmail] = useState('');
const [favoriteColor, setFavoriteColor] = useState('');

const handleSubmit = async () => {
  try {
    await updateUserAttributes({ email, 'custom:favorite_color': favoriteColor });
    alert('Attributes updated successfully!');
  } catch (error) {
    console.error('Error updating attributes:', error);

return (
  <form onSubmit={handleSubmit}>
      onChange={(e) => setEmail(e.target.value)}
      onChange={(e) => setFavoriteColor(e.target.value)}
    <button type="submit">Update</button>

Customising Email and SMS Messages

Customising the email and SMS messages sent by AWS Cognito enhances the user experience by providing a branded and personalised touch.

Custom Message Triggers

1. Lambda Function for Custom Messages: Create an AWS Lambda function to customise messages.

2. Link Lambda to Cognito: Attach the Lambda function as a trigger in the AWS Cognito console.

exports.handler = async (event) => {
  if (event.triggerSource === 'CustomMessage_SignUp') {
    event.response.emailSubject = 'Welcome to MyApp!';
    event.response.emailMessage = 'Thank you for signing up, ${event.request.userAttributes.name}!';
  return event;

Leveraging Cognito User Pools and Identity Pools

Combining Cognito User Pools and Identity Pools allows for a seamless and secure authentication and authorization process, especially when accessing AWS services.

Configuring Identity Pools

1. Create an Identity Pool: In the AWS Cognito console, create an identity pool and link it to your user pool. This allows users authenticated through the user pool to assume roles defined in the identity pool.

2. Update Amplify Configuration: Include identity pool details in your Amplify configuration.

import { Amplify } from 'aws-amplify';
import awsExports from './aws-exports';

  Auth: {
    identityPoolId: 'us-west-2:12345678-1ab2-1234-56cd-78e9012345fgh',
    region: 'us-west-2',
    userPoolId: 'us-west-2_abcdefghi',
    userPoolWebClientId: '1h2j3k4l5m6n7o8p9q0r12345',

3. Use Identity Pool Credentials: Leverage the credentials from the identity pool to access other AWS services, such as S3 or DynamoDB.

import { Storage } from 'aws-amplify';

// Upload a file to S3
const uploadFile = async (file) => {
  try {
    await Storage.put('example.txt', file, {
      level: 'private',
      contentType: 'text/plain',
    alert('File uploaded successfully!');
  } catch (error) {
    console.error('Error uploading file:', error);


Exploring the advanced features of AWS Cognito and Amplify unlocks the full potential of secure and scalable authentication in React applications. From integrating social sign-ins and multi-factor authentication to managing user attributes and customising messages, Amplify and Cognito provide comprehensive tools for enhancing user experience and security. By leveraging these advanced techniques, developers can build robust and user-friendly applications that meet the highest standards of security and usability.

For further exploration and detailed documentation, visit the Amazon Amplify Documentation. Happy coding!

Alan NgFront-End Engineer

Get in Touch.

Let’s discuss how we can help with your cloud journey. Our experts are standing by to talk about your migration, modernisation, development and skills challenges.

Ilja Summala
Ilja’s passion and tech knowledge help customers transform how they manage infrastructure and develop apps in cloud.
Ilja Summala LinkedIn
Group CTO