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 Swift Downloads
func chilkatTest() {
var success: Bool = 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.
let app = CkoJsonObject()!
app.strict = true
success = app.loadFile(path: "qa_data/cognito/app.json")
if success != true {
print("Could not load Cognito app settings.")
return
}
if (app.jsonType(of: "region").intValue != 1) || (app.string(of: "region") == "") {
print("Missing or invalid region.")
return
}
if (app.jsonType(of: "user_pool_id").intValue != 1) || (app.string(of: "user_pool_id") == "") {
print("Missing or invalid user_pool_id.")
return
}
if (app.jsonType(of: "client_id").intValue != 1) || (app.string(of: "client_id") == "") {
print("Missing or invalid client_id.")
return
}
if (app.jsonType(of: "account_key").intValue != 1) || (app.string(of: "account_key") == "") {
print("Missing or invalid account_key.")
return
}
var clientId: String? = app.string(of: "client_id")
let endpoint = CkoStringBuilder()!
endpoint.append(value: "https://cognito-idp.")
endpoint.append(value: app.string(of: "region"))
endpoint.append(value: ".amazonaws.com/")
let http = CkoHttp()!
http.requireSslCertVerify = true
http.followRedirects = false
http.connectTimeout = 20
http.readTimeout = 60
let resp = CkoHttpResponse()!
let body = CkoJsonObject()!
let result = CkoJsonObject()!
result.strict = true
// "api" supports API sign-in and refresh rotation. "oauth" uses the Cognito domain.
var method: String? = "api"
if (method != "api") && (method != "oauth") {
print("Choose api or oauth.")
return
}
let cached = CkoJsonObject()!
cached.strict = true
success = cached.loadFile(path: "qa_data/tokens/cognito-user.json")
if success != true {
print("Could not load qa_data/tokens/cognito-user.json.")
return
}
if (cached.jsonType(of: "client_id").intValue != 1) || (cached.string(of: "client_id") == "") {
print("Missing or invalid client_id.")
return
}
if cached.string(of: "client_id") != app.string(of: "client_id") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if (cached.jsonType(of: "user_pool_id").intValue != 1) || (cached.string(of: "user_pool_id") == "") {
print("Missing or invalid user_pool_id.")
return
}
if cached.string(of: "user_pool_id") != app.string(of: "user_pool_id") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if (cached.jsonType(of: "account_key").intValue != 1) || (cached.string(of: "account_key") == "") {
print("Missing or invalid account_key.")
return
}
if cached.string(of: "account_key") != app.string(of: "account_key") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if (cached.jsonType(of: "refresh_token").intValue != 1) || (cached.string(of: "refresh_token") == "") {
print("Missing or invalid refresh_token.")
return
}
if method == "api" {
body.updateString(jsonPath: "ClientId", value: clientId)
body.updateString(jsonPath: "RefreshToken", value: cached.string(of: "refresh_token"))
// If device remembering is enabled, supply the confirmed DeviceKey from your device flow.
if (cached.jsonType(of: "device_key").intValue == 1) && (cached.string(of: "device_key") != "") {
body.updateString(jsonPath: "DeviceKey", value: cached.string(of: "device_key"))
}
http.setRequestHeader(name: "X-Amz-Target", value: "AWSCognitoIdentityProviderService.GetTokensFromRefreshToken")
success = http.httpJson(verb: "POST", url: endpoint.getAsString(), json: body, contentType: "application/x-amz-json-1.0", response: resp)
if resp.statusCode.intValue != 200 {
print("HTTP status: \(resp.statusCode.intValue)")
success = result.load(json: resp.bodyStr)
if success == true {
print("Error type: \(result.string(of: "__type")!)")
print("OAuth error: \(result.string(of: "error")!)")
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return
}
if success != true {
print("The HTTP exchange did not complete.")
return
}
success = result.load(json: resp.bodyStr)
if success != true {
print("Expected a JSON response.")
return
}
}
else {
if (app.jsonType(of: "domain").intValue != 1) || (app.string(of: "domain") == "") {
print("Missing or invalid domain.")
return
}
// This URL comes from trusted configuration, never from a token or user-supplied URL.
let tokenEndpoint = CkoStringBuilder()!
tokenEndpoint.append(value: app.string(of: "domain"))
tokenEndpoint.append(value: "/oauth2/token")
let req = CkoHttpRequest()!
req.httpVerb = "POST"
req.contentType = "application/x-www-form-urlencoded"
req.addParam(name: "grant_type", value: "refresh_token")
req.addParam(name: "client_id", value: clientId)
req.addParam(name: "refresh_token", value: cached.string(of: "refresh_token"))
success = http.httpReq(url: tokenEndpoint.getAsString(), request: req, response: resp)
if resp.statusCode.intValue != 200 {
print("HTTP status: \(resp.statusCode.intValue)")
success = result.load(json: resp.bodyStr)
if success == true {
print("Error type: \(result.string(of: "__type")!)")
print("OAuth error: \(result.string(of: "error")!)")
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return
}
if success != true {
print("The HTTP exchange did not complete.")
return
}
success = result.load(json: resp.bodyStr)
if success != true {
print("Expected a JSON response.")
return
}
}
let token = CkoJsonObject()!
if method == "api" {
token.updateString(jsonPath: "access_token", value: result.string(of: "AuthenticationResult.AccessToken"))
token.updateString(jsonPath: "id_token", value: result.string(of: "AuthenticationResult.IdToken"))
token.updateString(jsonPath: "token_type", value: result.string(of: "AuthenticationResult.TokenType"))
token.updateInt(jsonPath: "expires_in", value: result.int(of: "AuthenticationResult.ExpiresIn").intValue)
if result.hasMember(jsonPath: "AuthenticationResult.RefreshToken") == true {
token.updateString(jsonPath: "refresh_token", value: result.string(of: "AuthenticationResult.RefreshToken"))
}
}
else {
success = token.load(json: result.emit())
if success != true {
print("Could not copy the token response.")
return
}
}
if (token.jsonType(of: "access_token").intValue != 1) || (token.string(of: "access_token") == "") {
print("Missing or invalid access_token.")
return
}
if (token.jsonType(of: "id_token").intValue != 1) || (token.string(of: "id_token") == "") {
print("Missing or invalid id_token.")
return
}
if (token.jsonType(of: "expires_in").intValue != 2) || (token.int(of: "expires_in").intValue <= 0) {
print("Expected a positive token lifetime.")
return
}
if token.string(of: "token_type") != "Bearer" {
print("Expected Bearer tokens.")
return
}
// Rotation enabled: save the replacement. Rotation disabled: retain the old refresh token.
if token.hasMember(jsonPath: "refresh_token") == true {
if (token.jsonType(of: "refresh_token").intValue != 1) || (token.string(of: "refresh_token") == "") {
print("Missing or invalid refresh_token.")
return
}
}
else {
token.updateString(jsonPath: "refresh_token", value: cached.string(of: "refresh_token"))
}
if (cached.jsonType(of: "device_key").intValue == 1) && (cached.string(of: "device_key") != "") {
token.updateString(jsonPath: "device_key", value: cached.string(of: "device_key"))
}
token.updateString(jsonPath: "client_id", value: app.string(of: "client_id"))
token.updateString(jsonPath: "user_pool_id", value: app.string(of: "user_pool_id"))
token.updateString(jsonPath: "account_key", value: app.string(of: "account_key"))
let obtained = CkoDateTime()!
success = obtained.setFromCurrentSystemTime()
if success != true {
print("Could not get the acquisition time.")
return
}
token.updateString(jsonPath: "obtained_at", value: obtained.get(asTimestamp: false))
let tokenrefreshedusertokens = CkoFileAccess()!
success = tokenrefreshedusertokens.dirEnsureExists(dirPath: "qa_data/tokens")
if success != true {
print("Could not create the private cache directory.")
return
}
if tokenrefreshedusertokens.fileExists(path: "qa_data/tokens/cognito-user.json") == true {
success = tokenrefreshedusertokens.fileCopy(existingPath: "qa_data/tokens/cognito-user.json", newPath: "qa_data/tokens/cognito-user.json.bak", failIfExists: false)
if success != true {
print("Could not back up the existing cache.")
return
}
}
success = token.writeFile(path: "qa_data/tokens/cognito-user.json")
if success != true {
print("Could not save refreshed user tokens; preserve any previous backup.")
return
}
print("Tokens refreshed; private cache updated.")
}