Setting Up Amazon Cognito in 5 Minutes

What is Amazon Cognito and how do I integrate my frontend and backend for user authentication?IntroductionAmazon Cognito is a powerful identity and access management service from AWS, that simplifies authentication, authorisation, and user management f…


This content originally appeared on Level Up Coding - Medium and was authored by Josh Thorne

What is Amazon Cognito and how do I integrate my frontend and backend for user authentication?

Introduction

Amazon Cognito is a powerful identity and access management service from AWS, that simplifies authentication, authorisation, and user management for your web and mobile applications. With Cognito, you can quickly add sign-up, sign-in, and access control features to your apps, providing a secure user experience with minimal effort.

User Pools vs. Identity Pools: What’s the Difference?

Cognito provides two main features for user access and management: User Pools and Identity Pools. While these features can work together, they serve different purposes and have distinct functionalities.

User Pools: Authentication and User Management

A User Pool is essentially a user directory that handles user registration, authentication, and account recovery. When users sign up or sign in through a User Pool, Cognito issues a JSON Web Token (JWT), which can be used to authenticate the user within your application.

  • Centralised User Management: User Pools allow you to manage users centrally, whether they sign in with a username/password or via social identity providers like Google, Facebook, or Amazon. When using social sign-in, Cognito consolidates these identities, simplifying user management across multiple providers.
  • Security Features: User Pools also support advanced security features like Multi-Factor Authentication (MFA), account recovery mechanisms, and customisable sign-up/sign-in workflows, enhancing the security of your application.
  • Integration with AWS Services: While User Pools can authenticate users for your application, they do not grant access to AWS resources directly. However, they can be integrated with AWS services like API Gateway and Application Load Balancer (ALB) to authenticate requests.
User pools do not grant permissions to access AWS resources directly.

Identity Pools: Access to AWS Resources

An Identity Pool in Cognito provides temporary AWS credentials that allow users to access AWS services. These credentials are issued based on the identity of the user, which can come from a User Pool or an external identity provider such as Google, Facebook, or any OpenID Connect (OIDC) compatible service.

  • Federated Identities: Identity Pools support federated identities, allowing users authenticated through various providers to obtain temporary AWS credentials. This enables users to access AWS resources like S3, DynamoDB, and more, based on the permissions you define in AWS IAM roles.
  • Guest Access: Identity Pools also allow unauthenticated (guest) access, where users without an identity can be granted limited access to AWS resources. This is useful for allowing limited, anonymous interactions with your application.

Bringing It Together

So, how do you integrate Cognito to manage user sign-up/sign-in and provide access to AWS resources?

To enable users to sign up, sign in, and access AWS resources using Cognito, you typically use both User Pools and Identity Pools together:

  1. Authentication: Set up a User Pool to handle the sign-up and sign-in experience. This will provide the user with a JWT token upon successful authentication.
  2. Authorisation: Configure an Identity Pool to accept the JWT from the User Pool and exchange it for temporary AWS credentials. These credentials can then be used to access AWS resources based on the permissions associated with the Identity Pool.
Quick Tip: For streamlined user management, consolidate your users and identity providers within a User Pool. Then, link this User Pool to an Identity Pool to easily manage AWS credentials and resource access for your users.

For more details, you can refer to the official AWS documentation.

https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-integrating-user-pools-with-identity-pools.html

Hands-On Example: Implementing Cognito in Your App

In this example, we will create a simple login page with separate frontend and backend components, enabling users to sign up and sign in using AWS Cognito. We wil be using AWS CDK (Cloud Development Kit) to configure the backend and React for the frontend.

Quick Tip: AWS Amplify is an excellent alternative starting point if you want to quickly integrate Cognito into your mobile or web apps. Check out the Amplify documentation to get started.

Configuring the Backend

For the backend, we will utilise CDK to deploy a Cognito User Pool, which will manage the sign-up and sign-in processes for our application.

  1. Initialise a New CDK Project: Start by setting up a new CDK project with TypeScript as the language:
mkdir my-project
cd my-project
cdk init app — language typescript

2. Create a Cognito User Pool: In your stack, configure a new Cognito User Pool with the desired attributes:

const userPool = new cognito.UserPool(this, 'UserPool', {
userPoolName: 'MyUserPool',
// Allow users to sign themselves up
selfSignUpEnabled: true,
// Allow users to sign in using their username
signInAliases: { username: true },
// Automatically verify email addresses
autoVerify: { email: true },
// Standard attributes for the user pool
standardAttributes: {
email: {
// Email is required
required: true,
// Email can be updated
mutable: true,
},
},
// Sign-in is not case sensitive
signInCaseSensitive: false,
// Multi-factor authentication is optional
mfa: cognito.Mfa.OPTIONAL,
// Second factor for MFA can be SMS or OTP
mfaSecondFactor: {
sms: true,
otp: true,
},
// Account recovery via email only
accountRecovery: cognito.AccountRecovery.EMAIL_ONLY,
// Configure a password policy for the users
passwordPolicy: {
minLength: 8,
requireLowercase: true,
requireUppercase: true,
requireDigits: true,
requireSymbols: true,
tempPasswordValidity: cdk.Duration.days(7),
},
});

This User Pool will act as a directory for your users, handling registration and authentication.

3. Define an App Client: To enable your application to interact with the User Pool, define an App Client:

new cognito.UserPoolClient(this, 'UserPoolClient', {
userPool,
authFlows: {
userPassword: true,
},
});

4. Deploy the Backend:

cdk deploy

5. Retrieve User Pool and App Client IDs:

  • After deployment, navigate to the AWS Console, open the Cognito service, and locate your User Pool. Copy the User Pool ID.
  • Open the User Pool and click on the App Integration tab. This will display the User Pool Client you defined earlier.
  • Scroll down to the bottom of the page and note down the Client ID of the App Client.

Configuring the Frontend

Next, we will configure the frontend to use the Cognito User Pool for user authentication.

  1. Clone the Example Frontend Code: Start by cloning the AWS example repository:
git clone https://github.com/aws-doc-sdk-examples.git

2. Navigate to the React Cognito Example:

cd javascriptv3/example_code/cognito-identity-provider/scenarios/cognito-developer-guide-react-example/frontend-client

3. Update Configuration: In the frontend/src/config.json file, input the User Pool ID and the App Client ID you noted earlier and the region you deployed the stack to:

{
"region": "eu-west-1",
"userPoolId": "eu-west-1_cian1hNcI",
"clientId": "29bdjb8j7j6d4hgbs2081j1ran"
}

4. Run the Frontend Application:

npm run dev

Testing the Application

Your application should now be running in your browser at http://localhost:5173/login.

  1. Sign Up: Click the Sign Up button to create a new user. Enter a valid email address during the sign-up process. You will receive an email with a confirmation code.

2. Account Confirmation: After entering the confirmation code, you should see a modal confirming that your account has been successfully registered. You should then be able to sign in using the credentials you just created.

3. Verify User Creation: To see the effect of this in your AWS environment, navigate to the Users tab in your Cognito User Pool. Here, you should now see the new user you just registered, confirming that the User Pool is correctly handling user management.

Conclusion

Setting up user authentication with Amazon Cognito streamlines the process of managing sign-up, sign-in, and user access for your applications. By configuring a User Pool and integrating it with your frontend, you’ve established a secure and scalable authentication system. With Cognito, you can efficiently handle user management and focus on building features, knowing your application’s authentication is secure and reliable.

If you found this article useful please clap, follow or connect with me today! 👏

Setting Up Amazon Cognito in 5 Minutes was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Josh Thorne


Print Share Comment Cite Upload Translate Updates
APA

Josh Thorne | Sciencx (2024-09-04T09:52:33+00:00) Setting Up Amazon Cognito in 5 Minutes. Retrieved from https://www.scien.cx/2024/09/04/setting-up-amazon-cognito-in-5-minutes/

MLA
" » Setting Up Amazon Cognito in 5 Minutes." Josh Thorne | Sciencx - Wednesday September 4, 2024, https://www.scien.cx/2024/09/04/setting-up-amazon-cognito-in-5-minutes/
HARVARD
Josh Thorne | Sciencx Wednesday September 4, 2024 » Setting Up Amazon Cognito in 5 Minutes., viewed ,<https://www.scien.cx/2024/09/04/setting-up-amazon-cognito-in-5-minutes/>
VANCOUVER
Josh Thorne | Sciencx - » Setting Up Amazon Cognito in 5 Minutes. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/09/04/setting-up-amazon-cognito-in-5-minutes/
CHICAGO
" » Setting Up Amazon Cognito in 5 Minutes." Josh Thorne | Sciencx - Accessed . https://www.scien.cx/2024/09/04/setting-up-amazon-cognito-in-5-minutes/
IEEE
" » Setting Up Amazon Cognito in 5 Minutes." Josh Thorne | Sciencx [Online]. Available: https://www.scien.cx/2024/09/04/setting-up-amazon-cognito-in-5-minutes/. [Accessed: ]
rf:citation
» Setting Up Amazon Cognito in 5 Minutes | Josh Thorne | Sciencx | https://www.scien.cx/2024/09/04/setting-up-amazon-cognito-in-5-minutes/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.