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 Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.FileAccess;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpRequest;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.StringBuilder;
public class ChilkatExample {
public static void main(String[] args) {
boolean 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.
JsonObject app = new JsonObject();
app.setStrict(true);
try {
app.loadFile("qa_data/cognito/app.json");
} catch (ChilkatException e) {
System.out.println("Could not load Cognito app settings.");
return;
}
if ((app.jsonTypeOf("region") != 1) || ("".equals(app.stringOf("region")))) {
System.out.println("Missing or invalid region.");
return;
}
if ((app.jsonTypeOf("user_pool_id") != 1) || ("".equals(app.stringOf("user_pool_id")))) {
System.out.println("Missing or invalid user_pool_id.");
return;
}
if ((app.jsonTypeOf("client_id") != 1) || ("".equals(app.stringOf("client_id")))) {
System.out.println("Missing or invalid client_id.");
return;
}
if ((app.jsonTypeOf("account_key") != 1) || ("".equals(app.stringOf("account_key")))) {
System.out.println("Missing or invalid account_key.");
return;
}
String clientId = app.stringOf("client_id");
StringBuilder endpoint = new StringBuilder();
endpoint.append("https://cognito-idp.");
endpoint.append(app.stringOf("region"));
endpoint.append(".amazonaws.com/");
Http http = new Http();
http.setRequireSslCertVerify(true);
http.setFollowRedirects(false);
http.setConnectTimeout(20);
http.setReadTimeout(60);
HttpResponse resp = new HttpResponse();
JsonObject body = new JsonObject();
JsonObject result = new JsonObject();
result.setStrict(true);
// "api" supports API sign-in and refresh rotation. "oauth" uses the Cognito domain.
String method = "api";
if ((!"api".equals(method)) && (!"oauth".equals(method))) {
System.out.println("Choose api or oauth.");
return;
}
JsonObject cached = new JsonObject();
cached.setStrict(true);
try {
cached.loadFile("qa_data/tokens/cognito-user.json");
} catch (ChilkatException e) {
System.out.println("Could not load qa_data/tokens/cognito-user.json.");
return;
}
if ((cached.jsonTypeOf("client_id") != 1) || ("".equals(cached.stringOf("client_id")))) {
System.out.println("Missing or invalid client_id.");
return;
}
if (!cached.stringOf("client_id").equals(app.stringOf("client_id"))) {
System.out.println("Saved data belongs to another client, pool, or local account.");
return;
}
if ((cached.jsonTypeOf("user_pool_id") != 1) || ("".equals(cached.stringOf("user_pool_id")))) {
System.out.println("Missing or invalid user_pool_id.");
return;
}
if (!cached.stringOf("user_pool_id").equals(app.stringOf("user_pool_id"))) {
System.out.println("Saved data belongs to another client, pool, or local account.");
return;
}
if ((cached.jsonTypeOf("account_key") != 1) || ("".equals(cached.stringOf("account_key")))) {
System.out.println("Missing or invalid account_key.");
return;
}
if (!cached.stringOf("account_key").equals(app.stringOf("account_key"))) {
System.out.println("Saved data belongs to another client, pool, or local account.");
return;
}
if ((cached.jsonTypeOf("refresh_token") != 1) || ("".equals(cached.stringOf("refresh_token")))) {
System.out.println("Missing or invalid refresh_token.");
return;
}
if ("api".equals(method)) {
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) && (!"".equals(cached.stringOf("device_key")))) {
body.updateString("DeviceKey", cached.stringOf("device_key"));
}
http.setRequestHeader("X-Amz-Target", "AWSCognitoIdentityProviderService.GetTokensFromRefreshToken");
http.httpJson("POST", endpoint.getAsString(), body, "application/x-amz-json-1.0", resp);
if (resp.getStatusCode() != 200) {
System.out.println("HTTP status: " + resp.getStatusCode());
try {
result.load(resp.getBodyStr());
success = true;
} catch (ChilkatException e) {
success = false;
}
if (success) {
System.out.println("Error type: " + result.stringOf("__type"));
System.out.println("OAuth error: " + result.stringOf("error"));
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return;
}
if (!success) {
System.out.println("The HTTP exchange did not complete.");
return;
}
try {
result.load(resp.getBodyStr());
} catch (ChilkatException e) {
System.out.println("Expected a JSON response.");
return;
}
} else {
if ((app.jsonTypeOf("domain") != 1) || ("".equals(app.stringOf("domain")))) {
System.out.println("Missing or invalid domain.");
return;
}
// This URL comes from trusted configuration, never from a token or user-supplied URL.
StringBuilder tokenEndpoint = new StringBuilder();
tokenEndpoint.append(app.stringOf("domain"));
tokenEndpoint.append("/oauth2/token");
HttpRequest req = new HttpRequest();
req.setHttpVerb("POST");
req.setContentType("application/x-www-form-urlencoded");
req.addParam("grant_type", "refresh_token");
req.addParam("client_id", clientId);
req.addParam("refresh_token", cached.stringOf("refresh_token"));
http.httpReq(tokenEndpoint.getAsString(), req, resp);
if (resp.getStatusCode() != 200) {
System.out.println("HTTP status: " + resp.getStatusCode());
try {
result.load(resp.getBodyStr());
success = true;
} catch (ChilkatException e) {
success = false;
}
if (success) {
System.out.println("Error type: " + result.stringOf("__type"));
System.out.println("OAuth error: " + result.stringOf("error"));
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return;
}
if (!success) {
System.out.println("The HTTP exchange did not complete.");
return;
}
try {
result.load(resp.getBodyStr());
} catch (ChilkatException e) {
System.out.println("Expected a JSON response.");
return;
}
}
JsonObject token = new JsonObject();
if ("api".equals(method)) {
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());
} catch (ChilkatException e) {
System.out.println("Could not copy the token response.");
return;
}
}
if ((token.jsonTypeOf("access_token") != 1) || ("".equals(token.stringOf("access_token")))) {
System.out.println("Missing or invalid access_token.");
return;
}
if ((token.jsonTypeOf("id_token") != 1) || ("".equals(token.stringOf("id_token")))) {
System.out.println("Missing or invalid id_token.");
return;
}
if ((token.jsonTypeOf("expires_in") != 2) || (token.intOf("expires_in") <= 0)) {
System.out.println("Expected a positive token lifetime.");
return;
}
if (!"Bearer".equals(token.stringOf("token_type"))) {
System.out.println("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) || ("".equals(token.stringOf("refresh_token")))) {
System.out.println("Missing or invalid refresh_token.");
return;
}
} else {
token.updateString("refresh_token", cached.stringOf("refresh_token"));
}
if ((cached.jsonTypeOf("device_key") == 1) && (!"".equals(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"));
DateTime obtained = new DateTime();
try {
obtained.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not get the acquisition time.");
return;
}
token.updateString("obtained_at", obtained.getAsTimestamp(false));
FileAccess tokenrefreshedusertokens = new FileAccess();
try {
tokenrefreshedusertokens.dirEnsureExists("qa_data/tokens");
} catch (ChilkatException e) {
System.out.println("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);
} catch (ChilkatException e) {
System.out.println("Could not back up the existing cache.");
return;
}
}
try {
token.writeFile("qa_data/tokens/cognito-user.json");
} catch (ChilkatException e) {
System.out.println("Could not save refreshed user tokens; preserve any previous backup.");
return;
}
System.out.println("Tokens refreshed; private cache updated.");
}
}