Amazon Cognito: Sign In with Managed Login and PKCE
See more Amazon Cognito Examples
Configure a User Pool domain and a public app client with no secret. Enable the authorization-code grant, the Cognito identity provider (or your configured IdP), and the requested openid, email, and aws.cognito.signin.user.admin scopes. Register http://localhost:3017/ exactly as an allowed callback URL. Chilkat receives the local callback and manages state and S256 PKCE; no hosted callback service is needed. Use the system browser, not a password form embedded in your application.
The self-service admin scope permits user operations such as TOTP enrollment; it does not grant IAM administration. Cognito code flow returns refresh tokens without offline_access. A public desktop client must not contain a client secret. Web/mobile applications need their own appropriate callback handling. Tokens are saved privately; decoding their claims is not validation.
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 CkPerl Downloads
use chilkat();
$success = 0;
# Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = 0;
# App settings are trusted configuration. Keep a separate account_key/cache per local user.
$app = chilkat::CkJsonObject->new();
$app->put_Strict(1);
$success = $app->LoadFile("qa_data/cognito/app.json");
if ($success != 1) {
print "Could not load Cognito app settings." . "\r\n";
exit;
}
if (($app->JsonTypeOf("region") != 1) or ($app->stringOf("region") == "")) {
print "Missing or invalid region." . "\r\n";
exit;
}
if (($app->JsonTypeOf("user_pool_id") != 1) or ($app->stringOf("user_pool_id") == "")) {
print "Missing or invalid user_pool_id." . "\r\n";
exit;
}
if (($app->JsonTypeOf("client_id") != 1) or ($app->stringOf("client_id") == "")) {
print "Missing or invalid client_id." . "\r\n";
exit;
}
if (($app->JsonTypeOf("account_key") != 1) or ($app->stringOf("account_key") == "")) {
print "Missing or invalid account_key." . "\r\n";
exit;
}
$clientId = $app->stringOf("client_id");
$endpoint = chilkat::CkStringBuilder->new();
$endpoint->Append("https://cognito-idp.");
$endpoint->Append($app->stringOf("region"));
$endpoint->Append(".amazonaws.com/");
if (($app->JsonTypeOf("domain") != 1) or ($app->stringOf("domain") == "")) {
print "Missing or invalid domain." . "\r\n";
exit;
}
# This URL comes from trusted configuration, never from a token or user-supplied URL.
$tokenEndpoint = chilkat::CkStringBuilder->new();
$tokenEndpoint->Append($app->stringOf("domain"));
$tokenEndpoint->Append("/oauth2/token");
$oauth = chilkat::CkOAuth2->new();
$authorizeEndpoint = chilkat::CkStringBuilder->new();
$authorizeEndpoint->Append($app->stringOf("domain"));
$authorizeEndpoint->Append("/oauth2/authorize");
$oauth->put_AuthorizationEndpoint($authorizeEndpoint->getAsString());
$oauth->put_TokenEndpoint($tokenEndpoint->getAsString());
$oauth->put_ClientId($clientId);
# Register exactly http://localhost:3017/ as an allowed callback for this public client.
$oauth->put_LocalHost("localhost");
$oauth->put_ListenPort(3017);
$oauth->put_CodeChallenge(1);
$oauth->put_CodeChallengeMethod("S256");
# Cognito does NOT use an offline_access scope. Code flow returns a refresh token.
$oauth->put_Scope("openid email aws.cognito.signin.user.admin");
$authUrl = $oauth->startAuth();
if ($oauth->get_LastMethodSuccess() != 1) {
print "Could not start the local OAuth listener." . "\r\n";
exit;
}
$success = $oauth->LaunchBrowser($authUrl);
if ($success != 1) {
$oauth->Cancel();
print "Could not launch the system browser." . "\r\n";
exit;
}
$waited = 0;
while ((($oauth->get_AuthFlowState() < 3) and ($waited < 180000))) {
$oauth->SleepMs(200);
$waited = $waited + 200;
}
if ($oauth->get_AuthFlowState() < 3) {
$oauth->Cancel();
print "Authorization timed out." . "\r\n";
exit;
}
if ($oauth->get_AuthFlowState() != 3) {
print "Authorization did not complete." . "\r\n";
exit;
}
$token = chilkat::CkJsonObject->new();
$token->put_Strict(1);
$success = $token->Load($oauth->accessTokenResponse());
if ($success != 1) {
print "Could not parse the token response." . "\r\n";
exit;
}
if (($token->JsonTypeOf("access_token") != 1) or ($token->stringOf("access_token") == "")) {
print "Missing or invalid access_token." . "\r\n";
exit;
}
if (($token->JsonTypeOf("id_token") != 1) or ($token->stringOf("id_token") == "")) {
print "Missing or invalid id_token." . "\r\n";
exit;
}
if (($token->JsonTypeOf("expires_in") != 2) or ($token->IntOf("expires_in") <= 0)) {
print "Expected a positive token lifetime." . "\r\n";
exit;
}
if ($token->stringOf("token_type") != "Bearer") {
print "Expected Bearer tokens." . "\r\n";
exit;
}
if (($token->JsonTypeOf("refresh_token") != 1) or ($token->stringOf("refresh_token") == "")) {
print "Missing or invalid refresh_token." . "\r\n";
exit;
}
$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"));
$obtained = chilkat::CkDateTime->new();
$success = $obtained->SetFromCurrentSystemTime();
if ($success != 1) {
print "Could not get the acquisition time." . "\r\n";
exit;
}
$token->UpdateString("obtained_at",$obtained->getAsTimestamp(0));
$tokenusertokens = chilkat::CkFileAccess->new();
$success = $tokenusertokens->DirEnsureExists("qa_data/tokens");
if ($success != 1) {
print "Could not create the private cache directory." . "\r\n";
exit;
}
if ($tokenusertokens->FileExists("qa_data/tokens/cognito-user.json") == 1) {
$success = $tokenusertokens->FileCopy("qa_data/tokens/cognito-user.json","qa_data/tokens/cognito-user.json.bak",0);
if ($success != 1) {
print "Could not back up the existing cache." . "\r\n";
exit;
}
}
$success = $token->WriteFile("qa_data/tokens/cognito-user.json");
if ($success != 1) {
print "Could not save user tokens; preserve any previous backup." . "\r\n";
exit;
}
print "Authorization completed; private token cache saved." . "\r\n";
# Validate JWT signatures and claims before trusting their contents:
# Validate a Cognito JWT.