Subsequent API calls using Authorization Code Grant in Cognito

0

Greetings,

I intend to build a web application and I am using Cognito for the authentication process. I am new to Cognito and so far have used the implicit grant flow. As far as I understand, when using implicit grant the App Client returns access tokens embedded in the callback URL which are usually extracted and stored in the browser's cookies for subsequent API calls.

Now, when using Authorization Code Grant, I understand that a code is returned in the callback URL after authentication, which is later sent to Cognito and Cognito returns an access token and ID token. However, it does not come clear to me how in this flow should one use these tokens for subsequent API calls.

For example, in a micro-services web application a user after logging in would like to use service A or service B which have their own API Gateway endpoints and somehow the user needs persistent/stored tokens to use these endpoints.

Thanks in advance.

1回答
0
承認された回答

Hi appsg,

The issue with implicit grant is essentially that your callback receive the access token as query string param. This represents a security risk and apart from pet projects, should be avoided for production workloads.

With Authentication grant instead, your call back will NOT receive the user pool generated access token, but an authorization code. Your application has to use that authorization code as part of a HTTP Post request to the Cognito TOKEN Endpoint (https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html).

The response of above POST call, will contain a response as this:

{ "access_token":"eyJra1example", "id_token":"eyJra2example", "refresh_token":"eyJj3example", "token_type":"Bearer", "expires_in":3600 }

From there, you can store those tokens in a DynamoDB encrypted database (https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html), which your app can pass as Bearer tokens in Authorization header when calling an HTTP REST API gateway.

Your application is responsible to reissue new tokens when expired (via refresh tokens), while the api gateway is responsible, via Cognito authorizers. This guide should help you through: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html

Hope it helps!

profile picture
エキスパート
回答済み 1年前
  • Awesome. The Dynamo DB part was the missing piece of the puzzle. I was struggling how tokens should be stored once issued since requiring the users to log in each time they need a token is not an option. Thanks a lot

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ