mrm
mrm

Reputation: 118

How to use cognito id token as authorization header for API gateway?

I have an API http gateway (at say https://example.com) integrated with an API REST gateway which uses a Cognito authorizer. All of this to serve a single-page React application. The behaviour is as expected:

Now my question is: how can I pass the header automatically after signing in so I can visit https://example.com?

I have spent a long time on this and have found many similar posts without an answer:

Upvotes: 1

Views: 3764

Answers (1)

Big Pumpkin
Big Pumpkin

Reputation: 4467

We faced the same question a couple of years ago. Our solution was creating a proxy (using API Gateway and Lambda) that "moved" the id_token (stored in a cookie) to the Authorization header for every request to the server. It was ugly, but it worked.

BTW, getting id_token in the URL is how Implicit Grant works. But Implicit Grant is generally considered less secure than Authorization Code Grant. We have since migrated from Implicit Grant to Authorization Code Grant. However, we continue to use the proxy pattern (again using API Gateway and Lambda) as follows.

  1. Exchange the returned code for access_token and id_token at the Cognito user pool's token endpoint. Store the tokens in a DynamoDB table with session_cookie as the partition key. Return the session_cookie as a cookie (with HttpOnly, Secure and SameSite=Strict) to the browser.
  2. For each request from the browser, use the cookie to find the token in the DynamoDB table and put the token in the Authorization header.

Upvotes: 0

Related Questions