Authentication & Authorization for Web Apps Using AWS Cognito

Satyajit Paul
The Startup
Published in
7 min readDec 31, 2019

Every application worth its salt needs Authentication & Authorization and fortunately, that problem is done & dusted by now. It doesn’t make sense for an application developer to reinvent the wheel anymore and I am sure no one is doing it today. When I started exploring AWS Cognito, realized there are multiple pieces to it. It took some time before I could connect various pieces and develop an understanding. So, I thought of writing them down at high level. I have also added a list of articles that I went through as part of my research.

In this blog we will see how we can use AWS Cognito for Authentication & Authorization for a Web App in completely serverless way. We will walk through the steps for enabling Signup, Signin and Authorization to access to an AWS Resource. At high level these are the things that you need to do —

  • Configure a Cognito User Pool for User Authentication process.
  • Configure a Cognito Identity Pool (Federated Identities) for Authorizing the users to AWS resources.
  • Configure IAM Policy for what AWS Resources that users can access.
  • Configure the specific AWS resource, in our case it will be AWS S3.
  • Start using the AWS Cognito Authentication/Authorization in your Web App.
Photo by Kelly Sikkema on Unsplash

Create Cognito Userpool

  • Create the User Pool in the same region as the WebApp and S3 Bucket. Note down following parameters

Pool Id ap-south-1_XXXXX40

App client id v9xxxxxxbb6mvyyyyyyvm7hb

  • Under General Settings > App Clients, make sure you uncheck “Generate client secret” if you want to use it from browser.
  • Under App Integration > App Client Settings, configure Callback and Sign out URLs. The URLs must be ‘https’, with exception of urls with localhost where ‘http’ is allowed.
  • Under App Integration>Domain Name, configure Amazon Cognito domain. This is used in Hosted URL for Signin. You may use your own domain name as well.
  • Next, under App Integration > App Client Settings, do OAuth2.0 settings based on your need.
  • “Authorization code grant” enables return of Auth code as response and “Implicit grant” enables return of Tokens like id_token or access_token in the response url.
  • Finally, you get a AWS Hosted URL that can be directly used in your Web App. Here are two different types of URL that AWS will provide.

https://salarymattersin.auth.ap-south-1.amazoncognito.com/login?client_id=v9h8g5e0bb6mvdmt0ps7vm7hb&response_type=token&scope=aws.cognito.signin.user.admin+email+openid+phone&redirect_uri=http://localhost:8080/aws-s3-from-browser.html

https://salarymattersin.auth.ap-south-1.amazoncognito.com/login?client_id=v9h8g5e0bb6mvdmt0ps7vm7hb&response_type=code&scope=aws.cognito.signin.user.admin+email+openid+phone&redirect_uri=http://localhost:8080/aws-s3-from-browser.html

  • You can do some amount of customization of the default UI in App Integration > UI Customization.

Create Cognito Identity Pool

  • In Identity Pool you need to configure IAM Roles for Unautheticated as well as Authenticated users. We will allow only Authenticated Users and hence, unchecked the checkbox used for enabling the access for Unauthenticated users. The IAM Role created for the Identity Pool needs to have access to the respective AWS Resources.
  • You need to configure the Authentication Provider here. In my case it was, AWS Cognito i.e. Cognito Userpool created earlier.

Configure IAM Policy

  • Provide AWS Resource Access for the IAM Role used in Identity Pool for the Authenticated users — Cognito_salarymattersAuth_Final_Role in the example above.
  • Like AWS S3, you can configure access to other AWS resources like AWS DynamoDB or Polly here.

Configure the AWS resource

  • Configure CORS Configuration for S3 Bucket. Please ensure the s3 Bucket is in the same region as Cognito User Pool and Identity Pool.

Setup your Web App to use Cognito based Auth

  • Create a Login Hyperlink/Button to call the Hosted Url with response_type=token shown above.
  • User is prompted to login. Post successful login, it redirects to the configured url with parameters like id_token, access_token etc after the #.
  • Read id_token from the url & use that to set up the AWS Config.

Below are some sample code for illustration pupose to give you an idea on what you may need to code in Javascript. For complete samples, refer to this.

In this example, we used AWS Cognito Hosted UI for Signup/Signin. But you may like to write your own UI and in that case AWS Cognito provides appropriate APIs to authenticate a user using username/password and setup AWS Cognito credentials.

Summary

If you have completed above activities, then you have created a Cognito User Pool which will take care of user Signup & Signin process. A fully functional User Pool will get you — a Hosted URL, User Pool Id, App Client ID. Hosted URL can be directly used in your Web App and you don’t have to do any additional UI code for handling things like — User Registration, Login, Password reset, Multi-Factor Authentication etc. You then use the User Pool Id, App Client ID to configure the Identity Pool (Federated Identities). Once Identity Pool is configured appropriately, you will have Identity Pool Id and a newly created IAM Policy. Configure IAM Policy to get necessary access to AWS Resource, in our case it was Full Access AWS S3. For any actual application, I am sure you will limit the access to a specific an S3 bucket and most likely to limited operations. Finally, to enable access from Web Browser, you configure the CORS Policy for S3. You are all set. In your web app, you will use User Pool Id, Identity Pool Id and id_token from response to setup Cognito Credentials. Finally, you initialize AWS S3 & use that for programmatic access to AWS Resource directly from browser.

References:

https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album.html

A complete AWS Documentation for using Cognito Authentication/Authorization to upload photos to an S3 Bucket in completely Serverless way.

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

Article shows how to access AWS Services Using an Identity Pool After Sign-in, helps with integrating a User Pool with an Identity Pool.

https://medium.com/@haydnjmorris/uploading-photos-to-aws-s3-getting-started-with-cognito-and-iam-c96ba5b5496d

This article details out how one can upload photos to AWS S3 from browser directly. It shows how to Authenticate using Cognito Identity Pools and then upload to S3 bucket from browser. This approach doesn’t need any AWS Lambda or any other backend coding.

https://www.mydatahack.com/uploading-file-from-browser-to-s3-with-javascript/

Here is one more article that is on the same line as above and it shows the use of both Cognito User Pool & Identity Pools and gives a more complete example including code.

https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album.html

This Article covers two different implementations —

Use lambda function + API Gateway to generate a temporary access_key and access_key_id and use that from the browser to upload a file to S3 Bucket.

Use lambda function + API Gateway to generate a pre-signed url and then use the pre-signed url in html form submission to upload a file to S3 Bucket.

https://medium.com/@ashan.fernando/upload-files-to-aws-s3-using-signed-urls-fa0a0cf489db

This article discusses two approaches to implement uploading files directly to AWS S3 private bucket from browser, using AWS IAM Temporary Access Credentials and using a pre-signed POST policy.

https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html

This article talks about JWT Token Validation — AWS provided client side library takes care of it, it automatically refresh your ID and access tokens if there is a valid (non-expired) refresh token present, and the ID and access tokens have a minimum remaining validity of 5 minutes.

https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-browser.html

This article will help in case you want to use Amazon Polly for the Authenticated users.

https://aws.amazon.com/blogs/mobile/building-fine-grained-authorization-using-amazon-cognito-user-pools-groups/

This article gives step by step guide for calling AWS DynamoDB services post user Authentication using Cognito.

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

Article shows how use ID Token, Access Token & Refresh Token along with Cognito User Pool.

--

--