Sample code for 30+ languages & platforms
Python Requires Chilkat v11.6.0+

Amazon Cognito: Refresh Tokens with Rotation Support

See more Amazon Cognito Examples

Renew a user session without asking for the password again. Choose the default GetTokensFromRefreshToken JSON API or the OAuth refresh_token grant. Both support refresh-token rotation. REFRESH_TOKEN_AUTH is incompatible with rotation and is intentionally not used. With rotation disabled, retain the old refresh token when the response omits a replacement; with rotation enabled, save the new one before another refresh.

Use a public client without a secret, matching the initial sign-in. Managed-login sessions can use the OAuth endpoint. API-origin sessions can use OAuth refresh only when device remembering is disabled; otherwise use the API with the confirmed DeviceKey. This collection's password sign-in example assumes device remembering is disabled. Coordinate simultaneous refreshes and handle the configured retry grace period; expiration or revocation requires a new sign-in. Rotating does not extend the original refresh-token lifetime.

Uses direct Chilkat.Http requests to the regional Cognito User Pools JSON API. Public app-client operations do not use IAM signing. These examples use a public app client without a client secret; do not add administrative AWS credentials. For a confidential app client, implement the operation-specific SecretHash/SECRET_HASH or ClientSecret requirements on a trusted system.

Create qa_data/cognito/app.json with string fields region (for example us-west-2), user_pool_id, client_id, and account_key (your local account identifier). OAuth examples also require domain, the trusted HTTPS base URL of your Cognito domain, without a trailing slash. The region and user pool must match the app client. These examples use commercial AWS endpoints.

Sample cache/input files contain secrets. Use an access-controlled directory outside web content and source control, separate each local user/account, and serialize operations that modify the same cache. In a real application obtain passwords and codes through private UI instead of leaving them in files. Cache writes retain a .bak copy; protect and remove obsolete backups and challenge files after the flow. Production storage should provide atomic replacement and OS-backed secret protection. Never restore an old refresh token automatically after rotation. These examples do not require a hosted web server.

Checks transport completion, HTTP status, and required response fields before using results. Cognito often reports throttling, invalid codes, and authentication failures as HTTP 400. Present generic sign-in/recovery errors to users; keep detailed diagnostics private. Retry throttled reads with bounded backoff, but reconcile uncertain writes and refresh rotations before repeating them.

AWS documentation 1 | AWS documentation 2

Chilkat Python Downloads

Python
import sys
import chilkat2

success = False

# Assumes Chilkat is unlocked. See Global Unlock Sample.
success = False
# App settings are trusted configuration. Keep a separate account_key/cache per local user.
app = chilkat2.JsonObject()
app.Strict = True
success = app.LoadFile("qa_data/cognito/app.json")
if (success != True):
    print("Could not load Cognito app settings.")
    sys.exit()

if ((app.JsonTypeOf("region") != 1) or (app.StringOf("region") == "")):
    print("Missing or invalid region.")
    sys.exit()

if ((app.JsonTypeOf("user_pool_id") != 1) or (app.StringOf("user_pool_id") == "")):
    print("Missing or invalid user_pool_id.")
    sys.exit()

if ((app.JsonTypeOf("client_id") != 1) or (app.StringOf("client_id") == "")):
    print("Missing or invalid client_id.")
    sys.exit()

if ((app.JsonTypeOf("account_key") != 1) or (app.StringOf("account_key") == "")):
    print("Missing or invalid account_key.")
    sys.exit()

clientId = app.StringOf("client_id")
endpoint = chilkat2.StringBuilder()
endpoint.Append("https://cognito-idp.")
endpoint.Append(app.StringOf("region"))
endpoint.Append(".amazonaws.com/")
http = chilkat2.Http()
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 20
http.ReadTimeout = 60
resp = chilkat2.HttpResponse()
body = chilkat2.JsonObject()
result = chilkat2.JsonObject()
result.Strict = True
# "api" supports API sign-in and refresh rotation. "oauth" uses the Cognito domain.
method = "api"
if ((method != "api") and (method != "oauth")):
    print("Choose api or oauth.")
    sys.exit()

cached = chilkat2.JsonObject()
cached.Strict = True
success = cached.LoadFile("qa_data/tokens/cognito-user.json")
if (success != True):
    print("Could not load qa_data/tokens/cognito-user.json.")
    sys.exit()

if ((cached.JsonTypeOf("client_id") != 1) or (cached.StringOf("client_id") == "")):
    print("Missing or invalid client_id.")
    sys.exit()

if (cached.StringOf("client_id") != app.StringOf("client_id")):
    print("Saved data belongs to another client, pool, or local account.")
    sys.exit()

if ((cached.JsonTypeOf("user_pool_id") != 1) or (cached.StringOf("user_pool_id") == "")):
    print("Missing or invalid user_pool_id.")
    sys.exit()

if (cached.StringOf("user_pool_id") != app.StringOf("user_pool_id")):
    print("Saved data belongs to another client, pool, or local account.")
    sys.exit()

if ((cached.JsonTypeOf("account_key") != 1) or (cached.StringOf("account_key") == "")):
    print("Missing or invalid account_key.")
    sys.exit()

if (cached.StringOf("account_key") != app.StringOf("account_key")):
    print("Saved data belongs to another client, pool, or local account.")
    sys.exit()

if ((cached.JsonTypeOf("refresh_token") != 1) or (cached.StringOf("refresh_token") == "")):
    print("Missing or invalid refresh_token.")
    sys.exit()

if (method == "api"):
    body.UpdateString("ClientId",clientId)
    body.UpdateString("RefreshToken",cached.StringOf("refresh_token"))
    # If device remembering is enabled, supply the confirmed DeviceKey from your device flow.
    if ((cached.JsonTypeOf("device_key") == 1) and (cached.StringOf("device_key") != "")):
        body.UpdateString("DeviceKey",cached.StringOf("device_key"))

    http.SetRequestHeader("X-Amz-Target","AWSCognitoIdentityProviderService.GetTokensFromRefreshToken")
    success = http.HttpJson("POST",endpoint.GetAsString(),body,"application/x-amz-json-1.0",resp)
    if (resp.StatusCode != 200):
        print("HTTP status: " + str(resp.StatusCode))
        success = result.Load(resp.BodyStr)
        if (success == True):
            print("Error type: " + result.StringOf("__type"))
            print("OAuth error: " + result.StringOf("error"))

        # Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        sys.exit()

    if (success != True):
        print("The HTTP exchange did not complete.")
        sys.exit()

    success = result.Load(resp.BodyStr)
    if (success != True):
        print("Expected a JSON response.")
        sys.exit()

else:
    if ((app.JsonTypeOf("domain") != 1) or (app.StringOf("domain") == "")):
        print("Missing or invalid domain.")
        sys.exit()

    # This URL comes from trusted configuration, never from a token or user-supplied URL.
    tokenEndpoint = chilkat2.StringBuilder()
    tokenEndpoint.Append(app.StringOf("domain"))
    tokenEndpoint.Append("/oauth2/token")
    req = chilkat2.HttpRequest()
    req.HttpVerb = "POST"
    req.ContentType = "application/x-www-form-urlencoded"
    req.AddParam("grant_type","refresh_token")
    req.AddParam("client_id",clientId)
    req.AddParam("refresh_token",cached.StringOf("refresh_token"))
    success = http.HttpReq(tokenEndpoint.GetAsString(),req,resp)
    if (resp.StatusCode != 200):
        print("HTTP status: " + str(resp.StatusCode))
        success = result.Load(resp.BodyStr)
        if (success == True):
            print("Error type: " + result.StringOf("__type"))
            print("OAuth error: " + result.StringOf("error"))

        # Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        sys.exit()

    if (success != True):
        print("The HTTP exchange did not complete.")
        sys.exit()

    success = result.Load(resp.BodyStr)
    if (success != True):
        print("Expected a JSON response.")
        sys.exit()

token = chilkat2.JsonObject()
if (method == "api"):
    token.UpdateString("access_token",result.StringOf("AuthenticationResult.AccessToken"))
    token.UpdateString("id_token",result.StringOf("AuthenticationResult.IdToken"))
    token.UpdateString("token_type",result.StringOf("AuthenticationResult.TokenType"))
    token.UpdateInt("expires_in",result.IntOf("AuthenticationResult.ExpiresIn"))
    if (result.HasMember("AuthenticationResult.RefreshToken") == True):
        token.UpdateString("refresh_token",result.StringOf("AuthenticationResult.RefreshToken"))

else:
    success = token.Load(result.Emit())
    if (success != True):
        print("Could not copy the token response.")
        sys.exit()

if ((token.JsonTypeOf("access_token") != 1) or (token.StringOf("access_token") == "")):
    print("Missing or invalid access_token.")
    sys.exit()

if ((token.JsonTypeOf("id_token") != 1) or (token.StringOf("id_token") == "")):
    print("Missing or invalid id_token.")
    sys.exit()

if ((token.JsonTypeOf("expires_in") != 2) or (token.IntOf("expires_in") <= 0)):
    print("Expected a positive token lifetime.")
    sys.exit()

if (token.StringOf("token_type") != "Bearer"):
    print("Expected Bearer tokens.")
    sys.exit()

# Rotation enabled: save the replacement. Rotation disabled: retain the old refresh token.
if (token.HasMember("refresh_token") == True):
    if ((token.JsonTypeOf("refresh_token") != 1) or (token.StringOf("refresh_token") == "")):
        print("Missing or invalid refresh_token.")
        sys.exit()

else:
    token.UpdateString("refresh_token",cached.StringOf("refresh_token"))

if ((cached.JsonTypeOf("device_key") == 1) and (cached.StringOf("device_key") != "")):
    token.UpdateString("device_key",cached.StringOf("device_key"))

token.UpdateString("client_id",app.StringOf("client_id"))
token.UpdateString("user_pool_id",app.StringOf("user_pool_id"))
token.UpdateString("account_key",app.StringOf("account_key"))
obtained = chilkat2.CkDateTime()
success = obtained.SetFromCurrentSystemTime()
if (success != True):
    print("Could not get the acquisition time.")
    sys.exit()

token.UpdateString("obtained_at",obtained.GetAsTimestamp(False))
tokenrefreshedusertokens = chilkat2.FileAccess()
success = tokenrefreshedusertokens.DirEnsureExists("qa_data/tokens")
if (success != True):
    print("Could not create the private cache directory.")
    sys.exit()

if (tokenrefreshedusertokens.FileExists("qa_data/tokens/cognito-user.json") == True):
    success = tokenrefreshedusertokens.FileCopy("qa_data/tokens/cognito-user.json","qa_data/tokens/cognito-user.json.bak",False)
    if (success != True):
        print("Could not back up the existing cache.")
        sys.exit()

success = token.WriteFile("qa_data/tokens/cognito-user.json")
if (success != True):
    print("Could not save refreshed user tokens; preserve any previous backup.")
    sys.exit()

print("Tokens refreshed; private cache updated.")