How to use the code returned from Cognito to get AWS credentials?

arjabbar picture arjabbar · Aug 20, 2017 · Viewed 9k times · Source

Right now, I'm struggling to understand AWS Cognito so maybe someone could help me out. I set a domain to serve Cognito's hosted UI for my User Pool like what's described here. So when I go to https://<my-domain>.auth.us-east-1.amazoncognito.com/login?response_type=code&client_id=<MY_POOL_CLIENT_ID>&redirect_uri=https://localhost:8080 I get a login page where my users can login to my app with Google. That part is working great.

I confused about what to do with the code that is returned from that page once my user logs in. So once I get redirected to Google and authorize the application to view my information, I get redirected back to one of my URLs with a code in the query params. Right now I'm redirecting to localhost, so the redirect URL look like this:

https://localhost:8080/?code=XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX

What exactly is this code? Also, how do I use it to get access to AWS resources for my user?

Answer

Marcio Ghiraldelli picture Marcio Ghiraldelli · May 31, 2018

To fetch AWS credentials (id_token, access_token and refresh_token) from the code request parameter returned by the authorisation code oath2 flow, you should use your Cognito User Pool web domain /oauth2/token endpoint, following https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html instructions.

Pay attention to the HTTP Basic Authorisation user and password instructions, it should be your Cognito App client_id and client_secret, otherwise, you get a invalid_client error.

The code flow is supposed to be used server side, as you avoid tokens floating around on URLs. If you're planning to do that client side, you should use the response_type=token, as it gives this result directly on the login redirect.