Cognito User Pool: How to refresh Access Token using Refresh Token

前端 未结 7 1450
星月不相逢
星月不相逢 2020-12-12 23:23

I am using Cognito user pool to authenticate users in my system. A successful authentication gives an ID Token (JWT), Access Token (JWT) and a Refresh

7条回答
  •  心在旅途
    2020-12-13 00:04

    If you're in a situation where the Cognito Javascript SDK isn't going to work for your purposes, you can still see how it handles the refresh process in the SDK source:

    You can see in refreshSession that the Cognito InitiateAuth endpoint is called with REFRESH_TOKEN_AUTH set for the AuthFlow value, and an object passed in as the AuthParameters value.

    That object will need to be configured to suit the needs of your User Pool. Specifically, you may have to pass in your SECRET_HASH if your targeted App client id has an associated App client secret. User Pool Client Apps created for use with the Javascript SDK currently can't contain a client secret, and thus a SECRET_HASH isn't required to connect with them.

    Another caveat that might throw you for a loop is if your User Pool is set to remember devices, and you don't pass in the DEVICE_KEY along with your REFRESH_TOKEN. The Cognito API currently returns an "Invalid Refresh Token" error if you are passing in the RefreshToken without also passing in your DeviceKey. This error is returned even if you are passing in a valid RefreshToken. The thread linked above illuminates that, though I do hope AWS updates their error handling to be less cryptic in the future.

    As discussed in that thread, if you are using AdminInitiateAuth along with ADMIN_NO_SRP_AUTH, your successful authentication response payload does not currently contain NewDeviceMetadata; which means you won't have any DeviceKey to pass in as you attempt to refresh your tokens.

    My app calls for implementation in Python, so here's an example that worked for me:

    def refresh_token(self, username, refresh_token):
        try:
            return client.initiate_auth(
                ClientId=self.client_id,
                AuthFlow='REFRESH_TOKEN_AUTH',
                AuthParameters={
                    'REFRESH_TOKEN': refresh_token,
                    'SECRET_HASH': self.get_secret_hash(username)
                    # Note that SECRET_HASH is missing from JSDK
                    # Note also that DEVICE_KEY is missing from my example
                }
            )
        except botocore.exceptions.ClientError as e:
            return e.response
    

提交回复
热议问题