How do I set up an Amazon Cognito user pool as an authorizer on an API Gateway REST API?

8 minute read
5

I want to set up an Amazon Cognito user pool as an authorizer on my Amazon API Gateway REST API.

Short description

There are two ways to set up an Amazon Cognito user pool as an authorizer on an API Gateway REST API:

You can use either ID tokens or access tokens for authorization. Access tokens can authorize access to API Gateway APIs using custom scopes in Amazon Cognito. A Lambda authorizer can validate the claims in ID tokens and access tokens issued by Amazon Cognito.

For more information, see these topics:

Resolution

The following procedure shows how to create a COGNITO_USER_POOLS authorizer. The example assumes you already created two things:

Create a COGNITO_USER_POOLS authorizer

For more information, see Integrate a REST API with an Amazon Cognito user pool. Follow the instructions in the section To create a COGNITO_USER_POOLS authorizer by using the API Gateway console.

Test the new COGNITO_USER_POOLS authorizer

After you create the COGNITO_USER_POOLS authorizer, do the following:

1.    In the API Gateway console, choose the Test button under the new authorizer.

2.    In the Test window, for Authorization, enter an ID token from the new Amazon Cognito user pool.

3.    Choose Test.

Note: If the ID token is correct, then the test returns a 200 response code. An incorrect ID token returns a 401 response code.

Configure the COGNITO_USER_POOLS authorizer on an API method

For more information, see Integrate a REST API with an Amazon Cognito user pool. Follow the instructions in the section To configure a COGNITO_USER_POOLS authorizer on methods.

Get authorization tokens

There are four ways to get authorization tokens:

Note: Set up the Amazon Cognito hosted UI with an authorization code grant so your application can exchange the code for a token endpoint.

If you're using an implicit grant type, then you can obtain the grant from the callback URL. The callback URL is appended with the access token and ID token parameters for implicit flow. Make sure that you use the correct token type.

To get authorization tokens using the hosted UI for Amazon Cognito

To use the Authorization Code Grant flow, do the following:

Note: The response type parameter must be "code" when using the Authorization Code Grant flow.

1.    Send a GET request for an authorization code grant:

Important: Replace example_domain with the domain name of your user pool. Replace example_app_client_id with the app client ID of your user pool. Replace example_callback_url with your callback URL.

https://example_domain/oauth2/authorize?response_type=code&client_id=example_app_client_id&redirect_uri=example_callback_url

Note: Include the identity_provider parameter for the endpoint to redirect to the federated identity provider. If the app client is configured only for Amazon Cognito user pools, then the following endpoint redirects to the /login endpoint:

https://example_domain/login?response_type=code&client_id=example_app_client_id&redirect_uri=example_callback_url

2.    Sign in to your user pool or your federated identity provider. The user interface redirects to the URL specified in the callback for the app client.

Important: The redirection URL includes the authorization code that needs to be exchanged with the token endpoint to get valid tokens.

3.    Send a POST request to the /oauth2/token endpoint to exchange an authorization code for tokens. For more information, see Token endpoint.

Example POST request to exchange an authorization code for tokens

Note: The example POST request uses the following /oauth2/token endpoint: https://example_domain.auth.us-east-1.amazoncognito.com/oauth2/token&

Content-Type='application/x-www-form-urlencoded'&
Authorization=Basic ZXhhbXBsZTEyMzQ1Njc4OTA6enl4OTh3N3l2dHNycTY1NHBvMzIx
grant_type=authorization_code&
client_id=example1234567890&
code=AUTHORIZATION_CODE&
redirect_uri=com.myclientapp://myclient/redirect

Example POST request response

HTTP/1.1 200 OK 
Content-Type: application/json

{ 
  "access_token":"abCde1example", 
  "id_token":"abCde2example",
  "refresh_token":"abCde3example", 
  "token_type":"Bearer", 
  "expires_in":3600
}

To use the Implicit Grant flow, do the following:

Note: The response type parameter must be "token" when using the Implicit Grant flow.

1.    Send a GET request for an implicit grant:

Important: Replace example_domain with the domain name of your user pool. Replace example_app_client_id with the app client ID of your user pool. Replace example_callback_url with your callback URL.

https://example_domain/oauth2/authorize?response_type=token&client_id=example_app_client_id&redirect_uri=example_callback_url

Note: Include the identity_provider parameter for the endpoint to redirect to the federated identity provider. If the app client is configured only for Amazon Cognito user pools, then the following endpoint redirects to the /login endpoint:

https://example_domain/login?response_type=token&client_id=example_app_client_id&redirect_uri=example_callback_url

2.    Sign in to your user pool with the user name and password for an existing user, or create a new user for signing in. The user interface redirects to the URL specified in the callback for the app client.

Note: The redirection URL includes the ID token and access token.

Example redirection URL

https://www.example.com/#id_token=123456789idtoken123456789&access_token=123456789accesstoken123456789expires_in=3600&token_type=Bearer

To get authorization tokens using the AWS CLI

Note: If you receive errors when running AWS CLI commands, make sure that you're using the most recent AWS CLI version.

Run the following initiate-auth AWS CLI command to get authorization tokens:

Important: Replace example_user with your user name, example_password with your password, and example_app_client_id with your app client ID.

aws cognito-idp initiate-auth --auth-flow USER_PASSWORD_AUTH --auth-parameters USERNAME=example_user,PASSWORD=example_password --client_id example_app_client_id

Example initiate-auth AWS CLI command response

{
  "AuthenticationResult": {
    "AccessToken": "abCde1example",
    "IdToken": "abCde2example",
    "RefreshToken": "abCde3example",
    "TokenType": "Bearer",
    "ExpiresIn": 3600
  },
  "ChallengeParameters": {}
}

To get authorization tokens using one of the AWS SDKs

For more information see, Integrating Amazon Cognito with web and mobile apps.

To get authorization tokens using Postman

Use the OAuth 2.0 authorization mode in Postman to get authorization tokens. For more information, see Why am I getting API Gateway 401 Unauthorized errors after creating a Lambda authorizer?

Configure OAuth 2.0 custom scopes in Amazon Cognito user pools and verify scopes in API Gateway

A scope provides a level of access that an app can request of a resource. Amazon Cognito has built-in OAuth scopes that can be configured to allow an app client associated with a user pool. For more information about built-in scopes in Amazon Cognito, see App client settings terminology.

Custom scopes can be associated with OAuth 2.0 resource servers. For more information about resource servers, see Defining resource servers for your user pool.

When you use Amazon Cognito with API Gateway, the Amazon Cognito authorizer authenticates request and secures resources. Using custom scopes with Amazon Cognito and API Gateway helps you provide differentiated levels of access to your API resources. You also have more control when you expose resources to get access token scopes.

Configure a resource server and OAuth 2.0 custom scopes in a user pool

1.    Define the resource server and custom scopes for your user pool.
For the resource server Identifier, provide the HTTPS endpoint of the API Gateway where your resources are located.

2.    If necessary, configure a user pool app client and then add the custom scopes in the app client settings.

Note: A custom scope name is formatted as resourceServerIdentifier/scopeName

When a client app requests a custom scope in an OAuth 2.0 flow, the client app must request the full identifier for the scope. For example, if the resource server identifier is https://myresourceserver.example.com and the scope name is resources.read, the client app must request https://myresourceserver.example.com/resources.read at runtime.

Verify the OAuth 2.0 custom scopes in API Gateway

1.    Integrate a REST API with an Amazon Cognito user pool.

2.    In the API Gateway console, choose a REST API.

3.    In the Resources pane, choose a method name.

4.    Choose the Method Request configuration.

5.    From the Authorization dropdown list, choose Cognito Authorizer. This automatically adds a new field named OAuth Scopes.

6.    In the OAuth Scopes field, enter the full identifier for the custom scope in the format mentioned previously. For example, https://myresourceserver.example.com/resources.read.

7.    Save and deploy the API.

Test the setup using Postman or CURL

1.    Obtain the access token from the Amazon Cognito authorization server using one of the OAuth 2.0 flows defined for the client.

2.    Send the received access token you received as the authorization header in a request to API Gateway.

3.    If everything is successful and API Gateway validates and verifies the access token and the custom scope, then you get a 200 OK response.

Related information

Secure API access with Amazon Cognito Federated Identities, Amazon Cognito user pools, and Amazon API Gateway

How can I decode and verify the signature of an Amazon Cognito JSON Web Token?

Control access to a REST API using Amazon Cognito user pools as authorizer

AWS OFFICIAL
AWS OFFICIALUpdated 3 years ago
1 Comment

nice article

hemant
replied 7 months ago

Relevant content