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 Objective-C Downloads
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoStringBuilder.h>
#import <CkoOAuth2.h>
#import <CkoDateTime.h>
#import <CkoFileAccess.h>
BOOL success = NO;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = NO;
// App settings are trusted configuration. Keep a separate account_key/cache per local user.
CkoJsonObject *app = [[CkoJsonObject alloc] init];
app.Strict = YES;
success = [app LoadFile: @"qa_data/cognito/app.json"];
if (success != YES) {
NSLog(@"%@",@"Could not load Cognito app settings.");
return;
}
if (([[app JsonTypeOf: @"region"] intValue] != 1) || ([app StringOf: @"region"] == @"")) {
NSLog(@"%@",@"Missing or invalid region.");
return;
}
if (([[app JsonTypeOf: @"user_pool_id"] intValue] != 1) || ([app StringOf: @"user_pool_id"] == @"")) {
NSLog(@"%@",@"Missing or invalid user_pool_id.");
return;
}
if (([[app JsonTypeOf: @"client_id"] intValue] != 1) || ([app StringOf: @"client_id"] == @"")) {
NSLog(@"%@",@"Missing or invalid client_id.");
return;
}
if (([[app JsonTypeOf: @"account_key"] intValue] != 1) || ([app StringOf: @"account_key"] == @"")) {
NSLog(@"%@",@"Missing or invalid account_key.");
return;
}
NSString *clientId = [app StringOf: @"client_id"];
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"https://cognito-idp."];
[endpoint Append: [app StringOf: @"region"]];
[endpoint Append: @".amazonaws.com/"];
if (([[app JsonTypeOf: @"domain"] intValue] != 1) || ([app StringOf: @"domain"] == @"")) {
NSLog(@"%@",@"Missing or invalid domain.");
return;
}
// This URL comes from trusted configuration, never from a token or user-supplied URL.
CkoStringBuilder *tokenEndpoint = [[CkoStringBuilder alloc] init];
[tokenEndpoint Append: [app StringOf: @"domain"]];
[tokenEndpoint Append: @"/oauth2/token"];
CkoOAuth2 *oauth = [[CkoOAuth2 alloc] init];
CkoStringBuilder *authorizeEndpoint = [[CkoStringBuilder alloc] init];
[authorizeEndpoint Append: [app StringOf: @"domain"]];
[authorizeEndpoint Append: @"/oauth2/authorize"];
oauth.AuthorizationEndpoint = [authorizeEndpoint GetAsString];
oauth.TokenEndpoint = [tokenEndpoint GetAsString];
oauth.ClientId = clientId;
// Register exactly http://localhost:3017/ as an allowed callback for this public client.
oauth.LocalHost = @"localhost";
oauth.ListenPort = [NSNumber numberWithInt:3017];
oauth.CodeChallenge = YES;
oauth.CodeChallengeMethod = @"S256";
// Cognito does NOT use an offline_access scope. Code flow returns a refresh token.
oauth.Scope = @"openid email aws.cognito.signin.user.admin";
NSString *authUrl = [oauth StartAuth];
if (oauth.LastMethodSuccess != YES) {
NSLog(@"%@",@"Could not start the local OAuth listener.");
return;
}
success = [oauth LaunchBrowser: authUrl];
if (success != YES) {
[oauth Cancel];
NSLog(@"%@",@"Could not launch the system browser.");
return;
}
int waited = 0;
while ((([oauth.AuthFlowState intValue] < 3) && (waited < 180000))) {
[oauth SleepMs: [NSNumber numberWithInt: 200]];
waited = waited + 200;
}
if ([oauth.AuthFlowState intValue] < 3) {
[oauth Cancel];
NSLog(@"%@",@"Authorization timed out.");
return;
}
if ([oauth.AuthFlowState intValue] != 3) {
NSLog(@"%@",@"Authorization did not complete.");
return;
}
CkoJsonObject *token = [[CkoJsonObject alloc] init];
token.Strict = YES;
success = [token Load: oauth.AccessTokenResponse];
if (success != YES) {
NSLog(@"%@",@"Could not parse the token response.");
return;
}
if (([[token JsonTypeOf: @"access_token"] intValue] != 1) || ([token StringOf: @"access_token"] == @"")) {
NSLog(@"%@",@"Missing or invalid access_token.");
return;
}
if (([[token JsonTypeOf: @"id_token"] intValue] != 1) || ([token StringOf: @"id_token"] == @"")) {
NSLog(@"%@",@"Missing or invalid id_token.");
return;
}
if (([[token JsonTypeOf: @"expires_in"] intValue] != 2) || ([[token IntOf: @"expires_in"] intValue] <= 0)) {
NSLog(@"%@",@"Expected a positive token lifetime.");
return;
}
if ([token StringOf: @"token_type"] != @"Bearer") {
NSLog(@"%@",@"Expected Bearer tokens.");
return;
}
if (([[token JsonTypeOf: @"refresh_token"] intValue] != 1) || ([token StringOf: @"refresh_token"] == @"")) {
NSLog(@"%@",@"Missing or invalid refresh_token.");
return;
}
[token UpdateString: @"client_id" value: [app StringOf: @"client_id"]];
[token UpdateString: @"user_pool_id" value: [app StringOf: @"user_pool_id"]];
[token UpdateString: @"account_key" value: [app StringOf: @"account_key"]];
CkoDateTime *obtained = [[CkoDateTime alloc] init];
success = [obtained SetFromCurrentSystemTime];
if (success != YES) {
NSLog(@"%@",@"Could not get the acquisition time.");
return;
}
[token UpdateString: @"obtained_at" value: [obtained GetAsTimestamp: NO]];
CkoFileAccess *tokenusertokens = [[CkoFileAccess alloc] init];
success = [tokenusertokens DirEnsureExists: @"qa_data/tokens"];
if (success != YES) {
NSLog(@"%@",@"Could not create the private cache directory.");
return;
}
if ([tokenusertokens FileExists: @"qa_data/tokens/cognito-user.json"] == YES) {
success = [tokenusertokens FileCopy: @"qa_data/tokens/cognito-user.json" newPath: @"qa_data/tokens/cognito-user.json.bak" failIfExists: NO];
if (success != YES) {
NSLog(@"%@",@"Could not back up the existing cache.");
return;
}
}
success = [token WriteFile: @"qa_data/tokens/cognito-user.json"];
if (success != YES) {
NSLog(@"%@",@"Could not save user tokens; preserve any previous backup.");
return;
}
NSLog(@"%@",@"Authorization completed; private token cache saved.");
// Validate JWT signatures and claims before trusting their contents:
// Validate a Cognito JWT.