Sample code for 30+ languages & platforms
Lua 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 Lua Downloads

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- App settings are trusted configuration. Keep a separate account_key/cache per local user.
local app = chilkat.JsonObject.new()
app.strict = true
success = app:load_file("qa_data/cognito/app.json")
if not success then
    print("Could not load Cognito app settings.")
    return
end

if (app:json_type_of("region") ~= 1) or (app:string_of("region") == "") then
    print("Missing or invalid region.")
    return
end

if (app:json_type_of("user_pool_id") ~= 1) or (app:string_of("user_pool_id") == "") then
    print("Missing or invalid user_pool_id.")
    return
end

if (app:json_type_of("client_id") ~= 1) or (app:string_of("client_id") == "") then
    print("Missing or invalid client_id.")
    return
end

if (app:json_type_of("account_key") ~= 1) or (app:string_of("account_key") == "") then
    print("Missing or invalid account_key.")
    return
end

local clientId = app:string_of("client_id")
local endpoint = chilkat.StringBuilder.new()
endpoint:append("https://cognito-idp.")
endpoint:append(app:string_of("region"))
endpoint:append(".amazonaws.com/")
local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 20
http.read_timeout = 60
local resp = chilkat.HttpResponse.new()
local body = chilkat.JsonObject.new()
local result = chilkat.JsonObject.new()
result.strict = true
-- "api" supports API sign-in and refresh rotation. "oauth" uses the Cognito domain.
local method = "api"
if (method ~= "api") and (method ~= "oauth") then
    print("Choose api or oauth.")
    return
end

local cached = chilkat.JsonObject.new()
cached.strict = true
success = cached:load_file("qa_data/tokens/cognito-user.json")
if not success then
    print("Could not load qa_data/tokens/cognito-user.json.")
    return
end

if (cached:json_type_of("client_id") ~= 1) or (cached:string_of("client_id") == "") then
    print("Missing or invalid client_id.")
    return
end

if cached:string_of("client_id") ~= app:string_of("client_id") then
    print("Saved data belongs to another client, pool, or local account.")
    return
end

if (cached:json_type_of("user_pool_id") ~= 1) or (cached:string_of("user_pool_id") == "") then
    print("Missing or invalid user_pool_id.")
    return
end

if cached:string_of("user_pool_id") ~= app:string_of("user_pool_id") then
    print("Saved data belongs to another client, pool, or local account.")
    return
end

if (cached:json_type_of("account_key") ~= 1) or (cached:string_of("account_key") == "") then
    print("Missing or invalid account_key.")
    return
end

if cached:string_of("account_key") ~= app:string_of("account_key") then
    print("Saved data belongs to another client, pool, or local account.")
    return
end

if (cached:json_type_of("refresh_token") ~= 1) or (cached:string_of("refresh_token") == "") then
    print("Missing or invalid refresh_token.")
    return
end

if method == "api" then
    body:update_string("ClientId", clientId)
    body:update_string("RefreshToken", cached:string_of("refresh_token"))
    -- If device remembering is enabled, supply the confirmed DeviceKey from your device flow.
    if (cached:json_type_of("device_key") == 1) and (cached:string_of("device_key") ~= "") then
        body:update_string("DeviceKey", cached:string_of("device_key"))
    end

    http:set_request_header("X-Amz-Target", "AWSCognitoIdentityProviderService.GetTokensFromRefreshToken")
    success = http:http_json("POST", endpoint:get_as_string(), body, "application/x-amz-json-1.0", resp)
    if resp.status_code ~= 200 then
        print("HTTP status: " .. resp.status_code)
        success = result:load(resp.body_str)
        if success then
            print("Error type: " .. result:string_of("__type"))
            print("OAuth error: " .. result:string_of("error"))
        end

        -- Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        return
    end

    if not success then
        print("The HTTP exchange did not complete.")
        return
    end

    success = result:load(resp.body_str)
    if not success then
        print("Expected a JSON response.")
        return
    end
else
    if (app:json_type_of("domain") ~= 1) or (app:string_of("domain") == "") then
        print("Missing or invalid domain.")
        return
    end

    -- This URL comes from trusted configuration, never from a token or user-supplied URL.
    local tokenEndpoint = chilkat.StringBuilder.new()
    tokenEndpoint:append(app:string_of("domain"))
    tokenEndpoint:append("/oauth2/token")
    local req = chilkat.HttpRequest.new()
    req.http_verb = "POST"
    req.content_type = "application/x-www-form-urlencoded"
    req:add_param("grant_type", "refresh_token")
    req:add_param("client_id", clientId)
    req:add_param("refresh_token", cached:string_of("refresh_token"))
    success = http:http_req(tokenEndpoint:get_as_string(), req, resp)
    if resp.status_code ~= 200 then
        print("HTTP status: " .. resp.status_code)
        success = result:load(resp.body_str)
        if success then
            print("Error type: " .. result:string_of("__type"))
            print("OAuth error: " .. result:string_of("error"))
        end

        -- Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        return
    end

    if not success then
        print("The HTTP exchange did not complete.")
        return
    end

    success = result:load(resp.body_str)
    if not success then
        print("Expected a JSON response.")
        return
    end
end

local token = chilkat.JsonObject.new()
if method == "api" then
    token:update_string("access_token", result:string_of("AuthenticationResult.AccessToken"))
    token:update_string("id_token", result:string_of("AuthenticationResult.IdToken"))
    token:update_string("token_type", result:string_of("AuthenticationResult.TokenType"))
    token:update_int("expires_in", result:int_of("AuthenticationResult.ExpiresIn"))
    if result:has_member("AuthenticationResult.RefreshToken") then
        token:update_string("refresh_token", result:string_of("AuthenticationResult.RefreshToken"))
    end
else
    success = token:load(result:emit())
    if not success then
        print("Could not copy the token response.")
        return
    end
end

if (token:json_type_of("access_token") ~= 1) or (token:string_of("access_token") == "") then
    print("Missing or invalid access_token.")
    return
end

if (token:json_type_of("id_token") ~= 1) or (token:string_of("id_token") == "") then
    print("Missing or invalid id_token.")
    return
end

if (token:json_type_of("expires_in") ~= 2) or (token:int_of("expires_in") <= 0) then
    print("Expected a positive token lifetime.")
    return
end

if token:string_of("token_type") ~= "Bearer" then
    print("Expected Bearer tokens.")
    return
end

-- Rotation enabled: save the replacement. Rotation disabled: retain the old refresh token.
if token:has_member("refresh_token") then
    if (token:json_type_of("refresh_token") ~= 1) or (token:string_of("refresh_token") == "") then
        print("Missing or invalid refresh_token.")
        return
    end
else
    token:update_string("refresh_token", cached:string_of("refresh_token"))
end

if (cached:json_type_of("device_key") == 1) and (cached:string_of("device_key") ~= "") then
    token:update_string("device_key", cached:string_of("device_key"))
end

token:update_string("client_id", app:string_of("client_id"))
token:update_string("user_pool_id", app:string_of("user_pool_id"))
token:update_string("account_key", app:string_of("account_key"))
local obtained = chilkat.DateTime.new()
success = obtained:set_from_current_system_time()
if not success then
    print("Could not get the acquisition time.")
    return
end

token:update_string("obtained_at", obtained:get_as_timestamp(false))
local tokenrefreshedusertokens = chilkat.FileAccess.new()
success = tokenrefreshedusertokens:dir_ensure_exists("qa_data/tokens")
if not success then
    print("Could not create the private cache directory.")
    return
end

if tokenrefreshedusertokens:file_exists("qa_data/tokens/cognito-user.json") then
    success = tokenrefreshedusertokens:file_copy("qa_data/tokens/cognito-user.json", "qa_data/tokens/cognito-user.json.bak", false)
    if not success then
        print("Could not back up the existing cache.")
        return
    end
end

success = token:write_file("qa_data/tokens/cognito-user.json")
if not success then
    print("Could not save refreshed user tokens; preserve any previous backup.")
    return
end

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