Skip to content

React Website Authentication

The React Website Authentication generator adds authentication to your React website using Amazon Cognito.

This generator configures the CDK or Terraform infrastructure to create a Cognito User Pool and associated Identity Pool, as well as a hosted UI for handling user login flows, and its integration with your React website.

You can add authentication to your React website in two ways:

Terminal window
pnpm nx g @aws/nx-plugin:ts#website#auth
You can also perform a dry-run to see what files would be changed
Terminal window
pnpm nx g @aws/nx-plugin:ts#website#auth --dry-run
ParameterTypeDefaultDescription
project Requiredstring-The root directory of the website.
cognitoDomain string-The cognito domain prefix to use. If omitted, a value is derived from the npm scope and website project name.
allowSignup booleanWhether to allow self-signup
iac inherit | cdk | terraforminheritThe preferred IaC provider. By default this is inherited from your initial selection.
preferInstallDependencies booleantrueWhether to prefer installing dependencies after the generator runs. Set to false to defer installing when batching multiple generators (an install still runs if needed so subsequent generators can compute the Nx project graph); install once at the end.

You will find the following changes in your React website:

  • Directorysrc
    • Directorycomponents
      • DirectoryCognitoAuth
        • index.tsx Main authentication component
    • main.tsx Updated to instrument the CognitoAuth component

Since this generator vends infrastructure as code based on your chosen iac, it will create a project in packages/common which includes the relevant CDK constructs or Terraform modules.

The common infrastructure as code project is structured as follows:

  • Directorypackages/common/constructs
    • Directorysrc
      • Directoryapp/ Constructs for infrastructure specific to a project/generator
      • Directorycore/ Generic constructs which are reused by constructs in app
      • index.ts Entry point exporting constructs from app
    • project.json Project build targets and configuration

You will also find the following infrastructure code generated based on your selected iac:

  • Directorypackages/common/constructs/src
    • Directorycore
      • user-identity.ts Construct which defines the user pool and identity pool

This generator adds an Amazon Cognito user pool (for sign-in) and an identity pool (for federating signed-in users to scoped IAM credentials) to the existing static-website architecture:

Web BrowserWAFCognito(User + Identity Pool)Scoped IAMCredentialsAuthenticatedAWS Resources Sign in IAM/Cognito

The User Pool is created on the Cognito Plus feature plan with threat protection set to AUDIT mode for standard authentication. In audit mode, Cognito assigns a risk level to each sign-in and logs the assessment to CloudWatch without blocking users.

Once you have observed the risk assessments for your users, you can switch to full-function enforcement to automatically respond to risky activity (for example requiring MFA or blocking sign-in):

Set standardThreatProtectionMode to StandardThreatProtectionMode.FULL_FUNCTION in packages/common/constructs/src/core/user-identity.ts.

By default users must configure MFA (an SMS code or a time-based one time password) before they can sign in. You can make MFA optional, turn it off entirely, or restrict which second-factor methods are available:

import { Mfa } from 'aws-cdk-lib/aws-cognito';
new UserIdentity(this, 'Identity', {
mfa: Mfa.OPTIONAL,
mfaSecondFactor: { sms: false, otp: true },
});

mfa accepts Mfa.OFF / Mfa.OPTIONAL / Mfa.REQUIRED. mfaSecondFactor.sms and mfaSecondFactor.otp enable or disable each second-factor method independently; they have no effect when mfa is Mfa.OFF. Setting mfa: Mfa.REQUIRED with both methods disabled is rejected at synth time, since nobody could then complete sign-in.

By default the User Pool is associated with an AWS WAFv2 Web ACL using the AWSManagedRulesCommonRuleSet and AWSManagedRulesKnownBadInputsRuleSet managed rule groups. You can disable this if you wish to manage your own Web ACL or do not require one:

new UserIdentity(this, 'Identity', { enableWaf: false });

You will need to add the user identity infrastructure to your stack, declaring it before the website:

packages/infra/src/stacks/application-stack.ts
import { Stack } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { MyWebsite, UserIdentity } from '@my-scope/common-constructs';
export class ApplicationStack extends Stack {
constructor(scope: Construct, id: string) {
super(scope, id);
new UserIdentity(this, 'Identity');
new MyWebsite(this, 'MyWebsite');
}
}

The UserIdentity construct automatically adds the necessary Runtime Configuration to ensure that your website can point to the correct Cognito User Pool for authentication.

In order to grant authenticated users access to perform certain actions, such as granting permissions to invoke an API, you can add IAM policy statements to the identity pool authenticated role:

packages/infra/src/stacks/application-stack.ts
import { Stack } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { MyWebsite, UserIdentity, MyApi } from '@my-scope/common-constructs';
export class ApplicationStack extends Stack {
constructor(scope: Construct, id: string) {
super(scope, id);
const identity = new UserIdentity(this, 'Identity');
const api = new MyApi(this, 'MyApi', {
integrations: MyApi.defaultIntegrations(this).build(),
});
api.grantInvokeAccess(identity.identityPool.authenticatedRole);
new MyWebsite(this, 'MyWebsite');
}
}