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 use custom scopes in Amazon Cognito to authorize access to API Gateway APIs. A Lambda authorizer can validate the claims in ID tokens and access tokens issued by Amazon Cognito.

For more information, see the following topics:

Resolution

Prerequisites:

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

Complete the following steps:

  1. Open the API Gateway console.
  2. Under the new authorizer, choose the Test button.
  3. In the Test window, for Authorization, enter an ID token from the new Amazon Cognito user pool.
  4. 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 that your application can exchange the code for a token endpoint.

If you use 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 the implicit flow. Make sure that you use the correct token type.

Use the hosted UI for Amazon Cognito to get authorization tokens

Note: When you use the Authorization Code Grant flow, the response type parameter must be "code".

To use the Authorization Code Grant flow, complete the following steps:

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

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

    Note: 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. 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 must 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
}

Note: When you use the Implicit Grant flow, the response type parameter must be "token".

To use the Implicit Grant flow, complete the following steps:

  1. Send a GET request for an implicit grant:

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

    Note: 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. 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 username 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

Use the AWS CLI to get authorization tokens

Note: If you receive errors when you run AWS CLI commands, then see Troubleshoot AWS CLI errors. Also, make sure that you're using the most recent AWS CLI version.

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

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

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

Example initiate-auth AWS CLI command response

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

Use one of the AWS SDKs to get authorization tokens

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

Use Postman to get authorization tokens

Use the OAuth 2.0 authorization mode from the Postman website 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 terms.

Custom scopes can be associated with OAuth 2.0 resource servers. For more information about resource servers, see OAuth 2.0 scopes and API authorization with resource servers.

When you use Amazon Cognito with API Gateway, the Amazon Cognito authorizer authenticates request and secures resources. Use custom scopes with Amazon Cognito and API Gateway to 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.
  2. For the resource server Identifier, provide the HTTPS endpoint of the API Gateway where your resources are located.
  3. 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, then 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 previously mentioned. For example, https://myresourceserver.example.com/resources.read.
  7. Save and deploy the API.

Use Postman or CURL to test the setup

  1. To obtain the access token from the Amazon Cognito authorization server, use one of the OAuth 2.0 flows defined for the client.
  2. Send the received access token that you received as the authorization header in a request to API Gateway.

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 19 days ago
1 Comment

nice article

hemant
replied 10 months ago