Authorization by Cognito ID Pool after Authentication by User Pool – Authorization grant code ver

TOC

Authorization by Cognito ID Pool after Authentication by User Pool – Authorization grant code ver

In the following page, we have confirmed a configuration that uses Cognito user pool and identity pool, and OAuth flow grants the signed-in user access to AWS resources under the condition of Implicit grant.

あわせて読みたい
Authorization by Cognito ID Pool after Authentication by User Pool – Implicit Grant Ver 【Authorization by Cognito ID Pool after Authentication by User Pool - Implicit Grant Ver】 Use the Cognito user pool and identity pool to grant signed-in us...

This time, we will create a similar configuration with the OAuth flow set to Authorization code grant.

Environment

Diagram of Authorization by Cognito ID Pool after Authentication by User Pool - Aurhorization code grant ver

The configuration is the same as before.
The only change is to set the Oauth flow to Authorization code grant in the Cognito user pool.

Let’s check the flow of processing by Authorization code grant.
In the case of Authorization code grant, you cannot get a token directly, but can get an authorization code instead.
In this case, the following flow is used.Sign in from the hosted UI page.

obtain the authorization code from the URL parameter.
POST the authorization code to the token endpoint of the user pool to obtain a token.use the token to access the identity pool, obtain temporary credentials, and then access SSM.

For more information on token endpoints, please see the following page

  1. Sign in from the hosted UI page.
  2. Obtain the authorization code from the URL parameter.
  3. POST the authorization code to the token endpoint of the user pool to obtain a token.
  4. Use the token to access the identity pool, obtain temporary credentials, and then access SSM.

For more information on token endpoints, please see the following page

https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html

CloudFormation template files

The above configuration is built with CloudFormation.
The following URL contains the CloudFormation templates as well as browser scripts, etc.

https://github.com/awstut-an-r/awstut-fa/tree/main/035

Explanation of Key Points

Most of the configuration is the same as the previous one, so please refer to that for details.
This page covers the contents related to authorization code grant.

OAuth flow for Cognito user pool

Resources:
  UserPoolClient:
    Type: AWS::Cognito::UserPoolClient
    Properties:
      AllowedOAuthFlowsUserPoolClient: true
      AllowedOAuthFlows:
        - code
        #- implicit
      AllowedOAuthScopes:
        - openid
        - profile
      CallbackURLs:
        - !Sub "${BucketWesSiteEndpointUrl}/${SigninHtml}"
      ClientName: !Sub ${Prefix}-UserPoolClient
      ExplicitAuthFlows:
        - ALLOW_REFRESH_TOKEN_AUTH
        - ALLOW_USER_SRP_AUTH
      LogoutURLs:
        - !Sub "${BucketWesSiteEndpointUrl}/${SignoutHtml}"
      SupportedIdentityProviders:
        - COGNITO
      UserPoolId: !Ref UserPool
Code language: YAML (yaml)

Set the OAuth flow with the AllowedOAuthFlows property.
In this case, we will use Authorization code grant, so specify “code”.

Next, check the URLs of the sign-in/sign-out pages by the hosted UI.
The URLs are as follows

  • URL for sign-in page: https://[prefix].auth.ap-northeast-1.amazoncognito.com/login?response_type=code&client_id=[app client ID]&redirect_ uri=[URL to redirect to after sign-in].
  • URL for sign-out page: “https://[prefix].auth.ap-northeast-1.amazoncognito.com/logout?response_type=code&client_id=[app client ID]&logout_ uri=[URL to redirect to after signing out].

The key point is the URL parameter response_type.
In case of Authorization code grant, you can get the authorization code, so set this parameter to “code”.

Browser Script

Use JavaScript to implement Cognito functionality after sign-in.
For instructions on how to create a browser script using AWS SDK for JavaScript v3, please refer to the following page.

あわせて読みたい
Using AWS SDK for JavaScript v3 in Browser 【Using AWS SDK for JavaScript v3 in Browser】 When developing Web applications using AWS, the best practice is to use the AWS SDK for JavaScript.The SDK is ...

This page covers the key points to receive tokens by Authorization code grant.

Authorization code and token endpoint URL

Get the authorization code dispensed by the hosted UI.

const params = new URLSearchParams(window.location.search);
const code = params.get("code");

const tokenEndpoint = `https://${DOMAIN}.auth.${REGION}.amazoncognito.com/oauth2/token?grant_type=authorization_code&client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&code=${code}`;
Code language: JavaScript (javascript)

The authorization code can be obtained from the URL parameter.

Create a URL for the token endpoint.
Create a URL with the authorization code and other parameters embedded.

POST authorization code to token endpoint to obtain ID token

const main = async () => {
  await fetch(tokenEndpoint, {
    method: "post",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }})
    .then(response => {
      return response.json();
    })
    .then(data => {
      const idToken = data.id_token;
      ...
    })
};
Code language: JavaScript (javascript)

Using fetch, POST to the token endpoint URL you just created to retrieve the ID token.
The header must be “application/x-www-form-urlencoded” in the token endpoint requirements.

Use ID token to access identity pool and obtain temporary credentials

const ssmClient = new SSMClient({
region: REGION,
credentials: fromCognitoIdentityPool({
  client: new CognitoIdentityClient({ region: REGION }),
  identityPoolId: IDENTITY_POOL_ID,
  logins: {
    [`cognito-idp.${REGION}.amazonaws.com/${USER_POOL_ID}`]: idToken
  }
})
});

getParameter(ssmClient);
getName(idToken);
Code language: JavaScript (javascript)

The flow after this is the same as before.
The ID token is used to obtain a temporary credential from the ID pool.
This time, the objective is to obtain SSM parameters, so after creating the SSM client object, we access the parameter store.
In addition, we will also process to retrieve the user name from the ID token claim.

Architecting

Use CloudFormation to build this environment and verify actual behavior.

Create CloudFormation stacks and check resources in stacks

Create a CloudFormation stacks.
For information on how to create stacks and check each stack, please refer to the following page

あわせて読みたい
CloudFormation’s nested stack 【How to build an environment with a nested CloudFormation stack】 Examine nested stacks in CloudFormation. CloudFormation allows you to nest stacks. Nested ...

After reviewing the resources in each stack, the following is the information on the main resources created in this case.

  • Bucket name: fa-035
  • ID of Cognito user pool: ap-northeast-1_27X20ZW00
  • Cognito user pool app client ID: 2c45u7pnk8ubba6vf4otnubncv
  • Cognito user pool domain prefix: fa-035
  • ID of Cognito ID pool: ap-northeast-1:628252c8-3ed3-473d-9141-79bdf1cbd7ee
  • Parameter name in SSM parameter store: fa-035-authenticated

The AWS Management Console also checks the status of Cognito creation.

The Cognito user pool is successfully created.
Cognito user pool client successfully created.
OAuth authentication flow is set to "Authorization code grant".
The Cognito ID pool has been successfully created.

You can see that the “OAuth grant type” of the user pool client is set to “Authorization code grant”.

From the above, the URL for the sign-in/sign-out page with the hosted UI mentioned above is determined as follows.

  • URL for sign-in page: https://fa-035.auth.ap-northeast-1.amazoncognito.com/login?response_type=code&client_id=2c45u7pnk8ubba6vf4otnubncv& redirect_uri=https://s3-ap-northeast-1.amazonaws.com/fa-035/signin.html
  • URL for sign-out page: https://fa-012.auth.ap-northeast-1.amazoncognito.com/logout?response_type=token&client_id=2c45u7pnk8ubba6vf4 otnubncv&logout_uri=https://s3-ap-northeast-1.amazonaws.com/fa-035/signout.html

Accessing content for authenticated users

Now that we are ready, we can actually access the hosted UI.
Access the following URL

https://s3-ap-northeast-1.amazonaws.com/fa-035/index.html

The root page, index.html, will then be displayed.

Access the Cognito user pool sign-in page.

Press “Sign In” to display the sign-in page.

Only the first time, the sign-up process is required. For more information on the sign-up process, please refer to the following page.

あわせて読みたい
Create sign-in page in Cognito user pool 【Configure the hosted UI of the Cognito user pool to create a sign-in page】 Create a sign-in page using Cognito. Cognito is an authentication system servic...

In this case, we will register the user name “awstut”.
After entering your e-mail address and password, click “Sign In.

If you have successfully signed in, you can access AWS resources.

As with the Implicit grant, the user name and SSM parameter store values are now displayed.

Summary

Even when the OAuth flow is Authorization code grant, a token can be obtained by POST the authorization code to the Cognito token endpoint.
Then, by using the token to access the identity pool, it is possible to obtain temporary credentials that allow access to AWS resources.

TOC