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 Unicode C++ Downloads
#include <CkJsonObjectW.h>
#include <CkStringBuilderW.h>
#include <CkHttpW.h>
#include <CkHttpResponseW.h>
#include <CkHttpRequestW.h>
#include <CkDateTimeW.h>
#include <CkFileAccessW.h>
void ChilkatSample(void)
{
bool 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.
CkJsonObjectW app;
app.put_Strict(true);
success = app.LoadFile(L"qa_data/cognito/app.json");
if (success != true) {
wprintf(L"Could not load Cognito app settings.\n");
return;
}
if ((app.JsonTypeOf(L"region") != 1) || (app.stringOf(L"region") == L"")) {
wprintf(L"Missing or invalid region.\n");
return;
}
if ((app.JsonTypeOf(L"user_pool_id") != 1) || (app.stringOf(L"user_pool_id") == L"")) {
wprintf(L"Missing or invalid user_pool_id.\n");
return;
}
if ((app.JsonTypeOf(L"client_id") != 1) || (app.stringOf(L"client_id") == L"")) {
wprintf(L"Missing or invalid client_id.\n");
return;
}
if ((app.JsonTypeOf(L"account_key") != 1) || (app.stringOf(L"account_key") == L"")) {
wprintf(L"Missing or invalid account_key.\n");
return;
}
const wchar_t *clientId = app.stringOf(L"client_id");
CkStringBuilderW endpoint;
endpoint.Append(L"https://cognito-idp.");
endpoint.Append(app.stringOf(L"region"));
endpoint.Append(L".amazonaws.com/");
CkHttpW http;
http.put_RequireSslCertVerify(true);
http.put_FollowRedirects(false);
http.put_ConnectTimeout(20);
http.put_ReadTimeout(60);
CkHttpResponseW resp;
CkJsonObjectW body;
CkJsonObjectW result;
result.put_Strict(true);
// "api" supports API sign-in and refresh rotation. "oauth" uses the Cognito domain.
const wchar_t *method = L"api";
if ((method != L"api") && (method != L"oauth")) {
wprintf(L"Choose api or oauth.\n");
return;
}
CkJsonObjectW cached;
cached.put_Strict(true);
success = cached.LoadFile(L"qa_data/tokens/cognito-user.json");
if (success != true) {
wprintf(L"Could not load qa_data/tokens/cognito-user.json.\n");
return;
}
if ((cached.JsonTypeOf(L"client_id") != 1) || (cached.stringOf(L"client_id") == L"")) {
wprintf(L"Missing or invalid client_id.\n");
return;
}
if (cached.stringOf(L"client_id") != app.stringOf(L"client_id")) {
wprintf(L"Saved data belongs to another client, pool, or local account.\n");
return;
}
if ((cached.JsonTypeOf(L"user_pool_id") != 1) || (cached.stringOf(L"user_pool_id") == L"")) {
wprintf(L"Missing or invalid user_pool_id.\n");
return;
}
if (cached.stringOf(L"user_pool_id") != app.stringOf(L"user_pool_id")) {
wprintf(L"Saved data belongs to another client, pool, or local account.\n");
return;
}
if ((cached.JsonTypeOf(L"account_key") != 1) || (cached.stringOf(L"account_key") == L"")) {
wprintf(L"Missing or invalid account_key.\n");
return;
}
if (cached.stringOf(L"account_key") != app.stringOf(L"account_key")) {
wprintf(L"Saved data belongs to another client, pool, or local account.\n");
return;
}
if ((cached.JsonTypeOf(L"refresh_token") != 1) || (cached.stringOf(L"refresh_token") == L"")) {
wprintf(L"Missing or invalid refresh_token.\n");
return;
}
if (method == L"api") {
body.UpdateString(L"ClientId",clientId);
body.UpdateString(L"RefreshToken",cached.stringOf(L"refresh_token"));
// If device remembering is enabled, supply the confirmed DeviceKey from your device flow.
if ((cached.JsonTypeOf(L"device_key") == 1) && (cached.stringOf(L"device_key") != L"")) {
body.UpdateString(L"DeviceKey",cached.stringOf(L"device_key"));
}
http.SetRequestHeader(L"X-Amz-Target",L"AWSCognitoIdentityProviderService.GetTokensFromRefreshToken");
success = http.HttpJson(L"POST",endpoint.getAsString(),body,L"application/x-amz-json-1.0",resp);
if (resp.get_StatusCode() != 200) {
wprintf(L"HTTP status: %d\n",resp.get_StatusCode());
success = result.Load(resp.bodyStr());
if (success == true) {
wprintf(L"Error type: %s\n",result.stringOf(L"__type"));
wprintf(L"OAuth error: %s\n",result.stringOf(L"error"));
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return;
}
if (success != true) {
wprintf(L"The HTTP exchange did not complete.\n");
return;
}
success = result.Load(resp.bodyStr());
if (success != true) {
wprintf(L"Expected a JSON response.\n");
return;
}
}
else {
if ((app.JsonTypeOf(L"domain") != 1) || (app.stringOf(L"domain") == L"")) {
wprintf(L"Missing or invalid domain.\n");
return;
}
// This URL comes from trusted configuration, never from a token or user-supplied URL.
CkStringBuilderW tokenEndpoint;
tokenEndpoint.Append(app.stringOf(L"domain"));
tokenEndpoint.Append(L"/oauth2/token");
CkHttpRequestW req;
req.put_HttpVerb(L"POST");
req.put_ContentType(L"application/x-www-form-urlencoded");
req.AddParam(L"grant_type",L"refresh_token");
req.AddParam(L"client_id",clientId);
req.AddParam(L"refresh_token",cached.stringOf(L"refresh_token"));
success = http.HttpReq(tokenEndpoint.getAsString(),req,resp);
if (resp.get_StatusCode() != 200) {
wprintf(L"HTTP status: %d\n",resp.get_StatusCode());
success = result.Load(resp.bodyStr());
if (success == true) {
wprintf(L"Error type: %s\n",result.stringOf(L"__type"));
wprintf(L"OAuth error: %s\n",result.stringOf(L"error"));
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return;
}
if (success != true) {
wprintf(L"The HTTP exchange did not complete.\n");
return;
}
success = result.Load(resp.bodyStr());
if (success != true) {
wprintf(L"Expected a JSON response.\n");
return;
}
}
CkJsonObjectW token;
if (method == L"api") {
token.UpdateString(L"access_token",result.stringOf(L"AuthenticationResult.AccessToken"));
token.UpdateString(L"id_token",result.stringOf(L"AuthenticationResult.IdToken"));
token.UpdateString(L"token_type",result.stringOf(L"AuthenticationResult.TokenType"));
token.UpdateInt(L"expires_in",result.IntOf(L"AuthenticationResult.ExpiresIn"));
if (result.HasMember(L"AuthenticationResult.RefreshToken") == true) {
token.UpdateString(L"refresh_token",result.stringOf(L"AuthenticationResult.RefreshToken"));
}
}
else {
success = token.Load(result.emit());
if (success != true) {
wprintf(L"Could not copy the token response.\n");
return;
}
}
if ((token.JsonTypeOf(L"access_token") != 1) || (token.stringOf(L"access_token") == L"")) {
wprintf(L"Missing or invalid access_token.\n");
return;
}
if ((token.JsonTypeOf(L"id_token") != 1) || (token.stringOf(L"id_token") == L"")) {
wprintf(L"Missing or invalid id_token.\n");
return;
}
if ((token.JsonTypeOf(L"expires_in") != 2) || (token.IntOf(L"expires_in") <= 0)) {
wprintf(L"Expected a positive token lifetime.\n");
return;
}
if (token.stringOf(L"token_type") != L"Bearer") {
wprintf(L"Expected Bearer tokens.\n");
return;
}
// Rotation enabled: save the replacement. Rotation disabled: retain the old refresh token.
if (token.HasMember(L"refresh_token") == true) {
if ((token.JsonTypeOf(L"refresh_token") != 1) || (token.stringOf(L"refresh_token") == L"")) {
wprintf(L"Missing or invalid refresh_token.\n");
return;
}
}
else {
token.UpdateString(L"refresh_token",cached.stringOf(L"refresh_token"));
}
if ((cached.JsonTypeOf(L"device_key") == 1) && (cached.stringOf(L"device_key") != L"")) {
token.UpdateString(L"device_key",cached.stringOf(L"device_key"));
}
token.UpdateString(L"client_id",app.stringOf(L"client_id"));
token.UpdateString(L"user_pool_id",app.stringOf(L"user_pool_id"));
token.UpdateString(L"account_key",app.stringOf(L"account_key"));
CkDateTimeW obtained;
success = obtained.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not get the acquisition time.\n");
return;
}
token.UpdateString(L"obtained_at",obtained.getAsTimestamp(false));
CkFileAccessW tokenrefreshedusertokens;
success = tokenrefreshedusertokens.DirEnsureExists(L"qa_data/tokens");
if (success != true) {
wprintf(L"Could not create the private cache directory.\n");
return;
}
if (tokenrefreshedusertokens.FileExists(L"qa_data/tokens/cognito-user.json") == true) {
success = tokenrefreshedusertokens.FileCopy(L"qa_data/tokens/cognito-user.json",L"qa_data/tokens/cognito-user.json.bak",false);
if (success != true) {
wprintf(L"Could not back up the existing cache.\n");
return;
}
}
success = token.WriteFile(L"qa_data/tokens/cognito-user.json");
if (success != true) {
wprintf(L"Could not save refreshed user tokens; preserve any previous backup.\n");
return;
}
wprintf(L"Tokens refreshed; private cache updated.\n");
}