How to use AWS Cognito OAuth 2.0 Authorization code Flow?
This tutorial will discuss the OAuth flows in three parts, and you are reading Part 2. If you are interested about Implicit grant or if you missed the introduction please read AWS Cognito OAuth 2.0 Implicit Flow first.
Authorization code grant
I mentioned in our introduction the steps on how you can setup your App Client to use OAuth flows under App Integration setting. If you have not done this I suggest reading that section of the tutorial first.
To enable this grant put a check on Authorization code grant and click on Save Changes button. Also the App Client using this flow must NOT generate a Client Secret key, otherwise the authentication will not work.
Like the Implicit grant, this OAuth flow is also applicable for Front-End application. But instead of getting the user pool tokens directly, the Authorization code grant will return a separate authorization code that is then exchanged for the user pool tokens.
In this OAuth flow, the user pool tokens are not exposed to the end user, thus making it more secured than Implicit grant. But in order to get the user pool tokens you will need to submit an HTTP Post request to the TOKEN Endpoint using the authorization code.
Testing Using the Hosted UI
Now we can quickly test the Authorization code by using the Hosted UI. Click on Launch Hosted UI link at the bottom of the app settings panel.
You will get redirected to a Sign In page. Enter the Username and password of your test User. Again, if you have not created a test User, I have explained the steps in the first part of this tutorial.
On successful Sign In, you should get the authorization code in the Callback URL.
const cognitoAuth = new URLSearchParams(window.location.search); const authCode= cognitoAuth.get('code');
Here I’m using Postman to demonstrate the exchange of authorization code for user pool Tokens.
Form Request Body parameters:
grant_type – Must be authorization_code, the flow that we are using here. client_id – App Client ID in the User pool.
code – Authorization code grant, from the result of a successful Sign In.
redirect_url – This is the Callback URL in your App client.
The URL endpoint is something you can find in your User Pool profile. Under App Integration, go to Domain name. To complete the URL, append the path /oauth2/token to your domain.
As a result you will have a URL something like this example.
Submit an HTTP Post request with content type application/x-www-form-urlencoded. If you submitted a valid request, you should receive the user pool tokens.
Now you can use the tokens on succeeding requests, access_token to retrieve the USERINFO or the refresh_token in exchange for another batch of user pool tokens.
On the next topic AWS Cognito OAuth 2.0 Client credentials Flow, we will discuss the OAuth flow that is used for machine-to-machine authentication.