Skip to content

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

7 minute read
5

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

Short description

To set up an Amazon Cognito user pool as an authorizer on an API Gateway REST or HTTP API, create a COGNITO_USER_POOLS authorizer. Or, you can configure an AWS Lambda authorizer.

You can use 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.

Resolution

Note: If you receive errors when you run AWS Command Line Interface (AWS CLI) commands, then see Troubleshooting errors for the AWS CLI. Also, make sure that you're using the most recent AWS CLI version.

Prerequisites: Make sure that you configured an Amazon Cognito user pool with an app client. You must also have an existing API Gateway REST API or an API Gateway HTTP API.

Get authorization tokens

You can get authorization tokens in one of the following ways:

  • Use the authorization code grant flow in the Amazon Cognito hosted UI.
  • Use the implicit grant flow in the Amazon Cognito hosted UI.
  • Use the AWS CLI.
  • Use one of the AWS SDKs.
  • Use Postman.

Use the authorization code grant flow in the Amazon Cognito hosted UI

It's a best practice to use the authorization code grant flow. When you use the authorization code grant flow, the response type parameter must be code.

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 your third-party identity provider (IdP). 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 federate through your third-party IdP. The user interface redirects to the URL specified in the callback for the app client.
    Note: The redirection URL includes the authorization code that exchanges 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 ZXhhbXBsZTEyMzQ1Njc4OTA6enl4OTh3N3l2dHNycTY1NHBvMzIxgrant_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
    }

Use the implicit grant flow in the Amazon Cognito hosted UI

The implicit grant flow is a legacy authorization grant flow. When you use the implicit grant flow, the response type parameter must be token. For more information, see the Implicit grant section on OAuth 2.0 grants and The redirect and authorization endpoint.

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 your third-party IdP. 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. 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, run the following initiate-auth AWS CLI command:

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

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

For more information, see Authentication with AWS SDKs.

Use Postman

Use the OAuth 2.0 authorization mode from the Postman website to get authorization tokens. For more information, see Why do I get API Gateway "401 Unauthorized" errors after I create a Lambda authorizer?

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

Use custom scopes with Amazon Cognito and API Gateway to provide differentiated levels of access to your API resources.

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 more information, see the Defining a resource server for your user pool (AWS Management Console) section on About resource servers.
  2. For Resource server identifier, enter the HTTPS endpoint of the API Gateway where your resources are located.
  3. If necessary, then configure a user pool app client, and then add the custom scopes in the app client settings.
    Note: Use the resourceServerIdentifier/scopeName format for your custom scope name.

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.

Set up an Amazon Cognito user pool as an authorizer on a REST API

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

After you create a COGNITO_USER_POOLS authorizer in API Gateway, you can test the authorizer. To test the authorizer, choose your new authorizer, and then choose Test authorizer.

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

See Integrate a REST API with an Amazon Cognito user pool. Follow the instructions in the To configure a COGNITO_USER_POOLS authorizer on methods section.

To verify the OAuth 2.0 custom scopes in your API Gateway REST API, complete the following steps:

  1. Open the API Gateway console.
  2. Choose your REST API, and then choose your method.
  3. Under Method request settings, choose Edit.
  4. From the Authorization dropdown list, choose Cognito Authorizer.
  5. For OAuth Scopes, enter the full identifier for the custom scope. For example, https://myresourceserver.example.com/resources.read.
  6. Choose Save, and then choose Deploy API.

Set up an Amazon Cognito user pool as an authorizer on an HTTP API

Create a JWT authorizer, and then update a route to use a JWT authorizer.

To add authorization scopes to a route in your API Gateway HTTP API, complete the following steps:

  1. Open the API Gateway console.
  2. Select your HTTP API.
  3. In the navigation pane, choose Authorization.
  4. Under Attach authorizers to routes, choose the route.
  5. Under Authorization scopes, enter the scopes as user.email.
  6. Choose Save.

Note: If you don't use the default stage, then make sure that you deploy the API.

Use Postman or CURL to test the setup

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

If API Gateway validates and verifies the access token and the custom scope successfully, then you receive an HTTP 200 OK response.

Related information

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

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

Control access to REST APIs using Amazon Cognito user pools as an authorizer

How to secure API Gateway HTTP endpoints with JWT authorizer