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
전문가
답변함 일 년 전
  • 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

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인