Sample code for 30+ languages & platforms
PowerShell Requires Chilkat v11.6.0+

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 PowerShell Downloads

PowerShell
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"

$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.
$app = New-Object Chilkat.JsonObject
$app.Strict = $true
$success = $app.LoadFile("qa_data/cognito/app.json")
if ($success -ne $true) {
    $("Could not load Cognito app settings.")
    exit
}

if (($app.JsonTypeOf("region") -ne 1) -or ($app.StringOf("region") -eq "")) {
    $("Missing or invalid region.")
    exit
}

if (($app.JsonTypeOf("user_pool_id") -ne 1) -or ($app.StringOf("user_pool_id") -eq "")) {
    $("Missing or invalid user_pool_id.")
    exit
}

if (($app.JsonTypeOf("client_id") -ne 1) -or ($app.StringOf("client_id") -eq "")) {
    $("Missing or invalid client_id.")
    exit
}

if (($app.JsonTypeOf("account_key") -ne 1) -or ($app.StringOf("account_key") -eq "")) {
    $("Missing or invalid account_key.")
    exit
}

$clientId = $app.StringOf("client_id")
$endpoint = New-Object Chilkat.StringBuilder
$endpoint.Append("https://cognito-idp.")
$endpoint.Append($app.StringOf("region"))
$endpoint.Append(".amazonaws.com/")
if (($app.JsonTypeOf("domain") -ne 1) -or ($app.StringOf("domain") -eq "")) {
    $("Missing or invalid domain.")
    exit
}

#  This URL comes from trusted configuration, never from a token or user-supplied URL.
$tokenEndpoint = New-Object Chilkat.StringBuilder
$tokenEndpoint.Append($app.StringOf("domain"))
$tokenEndpoint.Append("/oauth2/token")
$oauth = New-Object Chilkat.OAuth2
$authorizeEndpoint = New-Object Chilkat.StringBuilder
$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 = 3017
$oauth.CodeChallenge = $true
$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"
$authUrl = $oauth.StartAuth()
if ($oauth.LastMethodSuccess -ne $true) {
    $("Could not start the local OAuth listener.")
    exit
}

$success = $oauth.LaunchBrowser($authUrl)
if ($success -ne $true) {
    $oauth.Cancel()
    $("Could not launch the system browser.")
    exit
}

$waited = 0
while ((($oauth.AuthFlowState -lt 3) -and ($waited -lt 180000))) {
    $oauth.SleepMs(200)
    $waited = $waited + 200
}

if ($oauth.AuthFlowState -lt 3) {
    $oauth.Cancel()
    $("Authorization timed out.")
    exit
}

if ($oauth.AuthFlowState -ne 3) {
    $("Authorization did not complete.")
    exit
}

$token = New-Object Chilkat.JsonObject
$token.Strict = $true
$success = $token.Load($oauth.AccessTokenResponse)
if ($success -ne $true) {
    $("Could not parse the token response.")
    exit
}

if (($token.JsonTypeOf("access_token") -ne 1) -or ($token.StringOf("access_token") -eq "")) {
    $("Missing or invalid access_token.")
    exit
}

if (($token.JsonTypeOf("id_token") -ne 1) -or ($token.StringOf("id_token") -eq "")) {
    $("Missing or invalid id_token.")
    exit
}

if (($token.JsonTypeOf("expires_in") -ne 2) -or ($token.IntOf("expires_in") -le 0)) {
    $("Expected a positive token lifetime.")
    exit
}

if ($token.StringOf("token_type") -ne "Bearer") {
    $("Expected Bearer tokens.")
    exit
}

if (($token.JsonTypeOf("refresh_token") -ne 1) -or ($token.StringOf("refresh_token") -eq "")) {
    $("Missing or invalid refresh_token.")
    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 = New-Object Chilkat.CkDateTime
$success = $obtained.SetFromCurrentSystemTime()
if ($success -ne $true) {
    $("Could not get the acquisition time.")
    exit
}

$token.UpdateString("obtained_at",$obtained.GetAsTimestamp($false))
$tokenusertokens = New-Object Chilkat.FileAccess
$success = $tokenusertokens.DirEnsureExists("qa_data/tokens")
if ($success -ne $true) {
    $("Could not create the private cache directory.")
    exit
}

if ($tokenusertokens.FileExists("qa_data/tokens/cognito-user.json") -eq $true) {
    $success = $tokenusertokens.FileCopy("qa_data/tokens/cognito-user.json","qa_data/tokens/cognito-user.json.bak",$false)
    if ($success -ne $true) {
        $("Could not back up the existing cache.")
        exit
    }

}

$success = $token.WriteFile("qa_data/tokens/cognito-user.json")
if ($success -ne $true) {
    $("Could not save user tokens; preserve any previous backup.")
    exit
}

$("Authorization completed; private token cache saved.")
#  Validate JWT signatures and claims before trusting their contents:
#  Validate a Cognito JWT.