DEV Community

Cover image for Seamless User Authentication: Integration of AWS Cognito with HTML/CSS and JavaScript
Rashi Agarwal for AWS Community Builders

Posted on

Seamless User Authentication: Integration of AWS Cognito with HTML/CSS and JavaScript

In the domain of web development, user authentication stands as a pivotal element ensuring application security and delivering a personalized user experience. AWS Cognito, a fully managed authentication service from AWS, simplifies the management of user identities and authentication processes. This blog post delves into the seamless integration of AWS Cognito with HTML, CSS, and JavaScript, enhancing the authentication journey within web applications.

Understanding AWS Cognito

Amazon Cognito offers a comprehensive solution for user identity management, allowing developers to handle user sign-up and sign-in, as well as manage user profiles and permissions. It supports various identity providers, including social identity providers such as Google and Facebook.

Key features of AWS Cognito include:

  • User Pools: User pools enable developers to create and manage a user directory where users can sign up, sign in, and manage their profiles.

  • Identity Pools: Identity pools (federated identities) allow users to obtain temporary AWS credentials to access AWS services.

  • Authentication: Supports multi-factor authentication (MFA) and various identity providers, providing flexibility in authentication methods.

  • Customizable UI: Developers can create a customized user interface for the authentication process.

Getting Started:

This demo will include creating a sign up/login page before accessing the website. The website is coded in HTML and javascript and we will be integrating AWS Cognito functionality in the sign up page.

STEP 1: Creating AWS Cognito user pool

For this follow the given steps:

  • Go to AWS Cognito console and choose Create User Pool.
  • In Provider types, choose Cognito user pool.

  • For the user sign-in options choose from the given options, suitable for your website sign up page.

  • Configure the options as per the requirement of the sign up page you are developing.

  • Now for the 5th step: Integrate your app: Enter the cognito pool name. Select the option Use the Cognito Hosted UI. Then select Use a cognito domain and enter the domain prefix, same as that of your user pool name.
    For the initial app client, select public client and enter app client name.
    It is important to add a callback URL, it's the URL that the user will be directed to once they have signed in.
    For example: http://localhost:8000/home.html

  • Now review the steps, and click create user pool.

  • You will get the cognito URL copy it.

STEP 2: Integrating AWS Cognito API with HTML Login Page

Image description
We'll look at a sample snippet of login page code wherein we'll call the AWS Cognito API.




<!DOCTYPE html>
<html lang="en">
<head>
<title>LogiN Page Sample </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">    
<link rel="icon" type="image/png" href="images/icons/favicon.ico"/>
<link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css">
<link rel="stylesheet" type="text/css" href="vendor/animate/animate.css">
<link rel="stylesheet" type="text/css" href="css/util.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>

    <div class="limiter">
        <div class="container-login100">
            <div class="wrap-login100">
                <form class="login100-form validate-form">
                    <span class="login100-form-title p-b-26">
                        Welcome to YourStyle
                    </span>

                    <div class="container-login100-form-btn">
                        <div class="wrap-login100-form-btn">
                            <div class="login100-form-bgbtn"></div>
                            <a class="<Insert AWS Cognito API>">
                            Login   </button>
                        </div>
                    </div>

                    <div class="text-center p-t-115">
                        <span class="txt1">
                            Dont have an account?
                        </span>

                        <a class="txt2" href="<Insert AWS Cognito API>">
                            Sign Up
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>


    <div id="dropDownSelect1"></div>

<script src="vendor/jquery/jquery-3.2.1.min.js"></script>
<script src="vendor/animsition/js/animsition.min.js"></script>
<script src="vendor/bootstrap/js/popper.js"></script>
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="vendor/select2/select2.min.js"></script>
<script src="vendor/daterangepicker/moment.min.js"></script>
<script src="vendor/daterangepicker/daterangepicker.js"></script>
<script src="vendor/countdowntime/countdowntime.js"></script>
<script src="js/main.js"></script>

</body>
</html>


Enter fullscreen mode Exit fullscreen mode

Now the crucial part here is how to insert the AWS Cognito API which will make the correct calls and give the required functionality. To integrate it follow the given syntax:



https://<aws cognito url>/login?response_type=code&client_id=<fetch from the user pool created>&redirect_uri=<callback url that you entered while creating the pool>


Enter fullscreen mode Exit fullscreen mode

Example would be:
https://homestyle.auth.us-east-1.amazoncognito.com/login?response_type=code&client_id=5icc2b3ks47a43hopdmbdoeqer&redirect_uri=http://localhost:8000/home.html

STEP 3: Creating YAML file for AWS Cognito
Name the YAML file in following way:
name_of_user_pool-cognito.yaml

Follow the given template syntax:



AWSTemplateFormatVersion: 2010-09-09 

Resources:
  UserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      AutoVerifiedAttributes:
        - email
      UsernameAttributes:
        - email
      UserPoolName: !Sub app_pool1
      Schema:
        - AttributeDataType: String
          Mutable: true
          Name: name
          Required: true

  UserPoolClient:
    Type: AWS::Cognito::UserPoolClient
    Properties:
      AccessTokenValidity: 60 # (minutes) default value.
      AllowedOAuthFlowsUserPoolClient: true
      AllowedOAuthFlows:
        - code
        - implicit
      AllowedOAuthScopes:
        - aws.cognito.signin.user.admin
        - email

      CallbackURLs:
        - !Sub "http://localhost:8000/home.html"
      ClientName: !Sub homestyle
      EnableTokenRevocation: true # default value.
      ExplicitAuthFlows:
        - ALLOW_CUSTOM_AUTH
        - ALLOW_REFRESH_TOKEN_AUTH
        - ALLOW_USER_SRP_AUTH
      IdTokenValidity: 60 # (minutes) default value.
      PreventUserExistenceErrors: ENABLED # default value.
      RefreshTokenValidity: 30 # (days) default value.
      SupportedIdentityProviders:
        - COGNITO
      TokenValidityUnits:
        AccessToken: minutes
        IdToken: minutes
        RefreshToken: days
      UserPoolId: !Ref us-east-1_WD8wX51gU

  UserPoolDomain:
    Type: AWS::Cognito::UserPoolDomain
    Properties:
      Domain: !Ref https://homestyle.auth.us-east-1.amazoncognito.com
      UserPoolId: !Ref us-east-1_WD8wX51gU


Enter fullscreen mode Exit fullscreen mode

From the above template, customize following fields:

  • Properties

  • UserPoolName

  • CallbackURLs

  • ClientName

  • UserPoolID

  • UserPoolDomain

In conclusion, integrating AWS Cognito with HTML, CSS, and JavaScript empowers developers to build secure and user-friendly authentication systems. With AWS Cognito's robust features and flexibility, you can tailor the authentication process to meet the specific requirements of your web application, providing a seamless and secure experience for your users. By following the steps outlined in this blog post, you can successfully integrate AWS Cognito and elevate the authentication standards of your web applications.

Top comments (0)