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 Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
var 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.
final app = CkJsonObject();
app.strict = true;
try {
app.loadFile('qa_data/cognito/app.json');
} on ChilkatException {
print('Could not load Cognito app settings.');
return;
}
if ((app.jsonTypeOf('region') != 1) || (app.stringOf('region') == '')) {
print('Missing or invalid region.');
return;
}
if ((app.jsonTypeOf('user_pool_id') != 1) || (app.stringOf('user_pool_id') == '')) {
print('Missing or invalid user_pool_id.');
return;
}
if ((app.jsonTypeOf('client_id') != 1) || (app.stringOf('client_id') == '')) {
print('Missing or invalid client_id.');
return;
}
if ((app.jsonTypeOf('account_key') != 1) || (app.stringOf('account_key') == '')) {
print('Missing or invalid account_key.');
return;
}
final clientId = app.stringOf('client_id');
final endpoint = CkStringBuilder();
endpoint.append('https://cognito-idp.');
endpoint.append(app.stringOf('region'));
endpoint.append('.amazonaws.com/');
final http = CkHttp();
http.requireSslCertVerify = true;
http.followRedirects = false;
http.connectTimeout = 20;
http.readTimeout = 60;
final resp = CkHttpResponse();
final body = CkJsonObject();
final result = CkJsonObject();
result.strict = true;
// "api" supports API sign-in and refresh rotation. "oauth" uses the Cognito domain.
final method = 'api';
if ((method != 'api') && (method != 'oauth')) {
print('Choose api or oauth.');
return;
}
final cached = CkJsonObject();
cached.strict = true;
try {
cached.loadFile('qa_data/tokens/cognito-user.json');
} on ChilkatException {
print('Could not load qa_data/tokens/cognito-user.json.');
return;
}
if ((cached.jsonTypeOf('client_id') != 1) || (cached.stringOf('client_id') == '')) {
print('Missing or invalid client_id.');
return;
}
if (cached.stringOf('client_id') != app.stringOf('client_id')) {
print('Saved data belongs to another client, pool, or local account.');
return;
}
if ((cached.jsonTypeOf('user_pool_id') != 1) || (cached.stringOf('user_pool_id') == '')) {
print('Missing or invalid user_pool_id.');
return;
}
if (cached.stringOf('user_pool_id') != app.stringOf('user_pool_id')) {
print('Saved data belongs to another client, pool, or local account.');
return;
}
if ((cached.jsonTypeOf('account_key') != 1) || (cached.stringOf('account_key') == '')) {
print('Missing or invalid account_key.');
return;
}
if (cached.stringOf('account_key') != app.stringOf('account_key')) {
print('Saved data belongs to another client, pool, or local account.');
return;
}
if ((cached.jsonTypeOf('refresh_token') != 1) || (cached.stringOf('refresh_token') == '')) {
print('Missing or invalid refresh_token.');
return;
}
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) && (cached.stringOf('device_key') != '')) {
body.updateString('DeviceKey', cached.stringOf('device_key'));
}
http.setRequestHeader('X-Amz-Target', 'AWSCognitoIdentityProviderService.GetTokensFromRefreshToken');
success = true;
try {
http.httpJson('POST', endpoint.getAsString(), body, 'application/x-amz-json-1.0', resp);
} on ChilkatException {
success = false;
}
if (resp.statusCode != 200) {
print('HTTP status: ${resp.statusCode}');
try {
result.load(resp.bodyStr);
print('Error type: ${result.stringOf('__type')}');
print('OAuth error: ${result.stringOf('error')}');
} on ChilkatException {
// result.load() failed; continue anyway.
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return;
}
if (!success) {
print('The HTTP exchange did not complete.');
return;
}
try {
result.load(resp.bodyStr);
} on ChilkatException {
print('Expected a JSON response.');
return;
}
} else {
if ((app.jsonTypeOf('domain') != 1) || (app.stringOf('domain') == '')) {
print('Missing or invalid domain.');
return;
}
// This URL comes from trusted configuration, never from a token or user-supplied URL.
final tokenEndpoint = CkStringBuilder();
tokenEndpoint.append(app.stringOf('domain'));
tokenEndpoint.append('/oauth2/token');
final req = CkHttpRequest();
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 = true;
try {
http.httpReq(tokenEndpoint.getAsString(), req, resp);
} on ChilkatException {
success = false;
}
if (resp.statusCode != 200) {
print('HTTP status: ${resp.statusCode}');
try {
result.load(resp.bodyStr);
print('Error type: ${result.stringOf('__type')}');
print('OAuth error: ${result.stringOf('error')}');
} on ChilkatException {
// result.load() failed; continue anyway.
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return;
}
if (!success) {
print('The HTTP exchange did not complete.');
return;
}
try {
result.load(resp.bodyStr);
} on ChilkatException {
print('Expected a JSON response.');
return;
}
}
final token = CkJsonObject();
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')) {
token.updateString('refresh_token', result.stringOf('AuthenticationResult.RefreshToken'));
}
} else {
try {
token.load(result.emit());
} on ChilkatException {
print('Could not copy the token response.');
return;
}
}
if ((token.jsonTypeOf('access_token') != 1) || (token.stringOf('access_token') == '')) {
print('Missing or invalid access_token.');
return;
}
if ((token.jsonTypeOf('id_token') != 1) || (token.stringOf('id_token') == '')) {
print('Missing or invalid id_token.');
return;
}
if ((token.jsonTypeOf('expires_in') != 2) || (token.intOf('expires_in') <= 0)) {
print('Expected a positive token lifetime.');
return;
}
if (token.stringOf('token_type') != 'Bearer') {
print('Expected Bearer tokens.');
return;
}
// Rotation enabled: save the replacement. Rotation disabled: retain the old refresh token.
if (token.hasMember('refresh_token')) {
if ((token.jsonTypeOf('refresh_token') != 1) || (token.stringOf('refresh_token') == '')) {
print('Missing or invalid refresh_token.');
return;
}
} else {
token.updateString('refresh_token', cached.stringOf('refresh_token'));
}
if ((cached.jsonTypeOf('device_key') == 1) && (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'));
final obtained = CkDateTime();
try {
obtained.setFromCurrentSystemTime();
} on ChilkatException {
print('Could not get the acquisition time.');
return;
}
token.updateString('obtained_at', obtained.getAsTimestamp(false));
final tokenrefreshedusertokens = CkFileAccess();
try {
tokenrefreshedusertokens.dirEnsureExists('qa_data/tokens');
} on ChilkatException {
print('Could not create the private cache directory.');
return;
}
if (tokenrefreshedusertokens.fileExists('qa_data/tokens/cognito-user.json')) {
try {
tokenrefreshedusertokens.fileCopy('qa_data/tokens/cognito-user.json', 'qa_data/tokens/cognito-user.json.bak', false);
} on ChilkatException {
print('Could not back up the existing cache.');
return;
}
}
try {
token.writeFile('qa_data/tokens/cognito-user.json');
} on ChilkatException {
print('Could not save refreshed user tokens; preserve any previous backup.');
return;
}
print('Tokens refreshed; private cache updated.');
}