Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate AWS Cognito session code returned from Cognito CustomUI login page

I configured Cognito to use the custom website that AWS Cognito provides for signup/signin as specified here:

https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-ui-customization.html

I am perfectly able to signup and login within the AWS Cognito page:

https://<your_domain>/login?response_type=code&client_id=<your_app_client_id>&redirect_uri=<your_callback_url>

The problem is that, after a successful login, Cognito redirect to the redirect page that I set, and the redirect includes a "code" value as a GET parameter.

I can not find documentation of how to use that "code" parameter, but it surely needs to be validated by my Python backend in order to check if that code is a valid session for a given user.

Can you provide a sample Python code (using or not a library, maybe Warrant) and JavaScript code that can validate that "code" parameter? and also to get the email/name of the user of that "code" parameter?

Thanks!!

like image 995
KGs Avatar asked Jan 31 '26 21:01

KGs


1 Answers

Since you are using Authorization Code Grant flow, it requires the following to be done in order to get a short lived id_token, long lived refresh_token and an access_token.

Note: This is the most difficult flow to implement. If you need a simplified authentication flow, use the implicit grant flow, which will return the id_token once the user logins with the login page.

For Authorization Code flow, it requires the following

  1. Receive Authorization Code from the Login Redirect URL. The code is not for recurrent use and only needs to be used to get the access tokens.
  2. This code can be exchanged for access tokens using a token endpoint provided by AWS Cognito. You need to send a HTTP POST request in the following format (Without PKCE).

    GET https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/authorize? response_type=code& client_id=ad398u21ijw3s9w3939& redirect_uri=https://YOUR_APP/redirect_uri& state=STATE& scope=openid+profile+aws.cognito.signin.user.admin

    For more details read the Token Endpoint documentation.

  3. After receiving the tokens, store the refresh_token in a safe place to get new id_tokens and use the id_token to access the APIs.

like image 168
Ashan Avatar answered Feb 02 '26 12:02

Ashan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!