Amazon Cognito: Validate a Cognito JWT
See more Amazon Cognito Examples
Validate an access token (default) or ID token using the configured pool's JWKS and Chilkat.Jwt/PublicKey. Explicitly allow RS256, select one matching kid, verify the signature, then check issuer, token_use, time claims, and the appropriate client claim: aud for ID tokens, client_id for access tokens. The access-token example also requires an exact scope. A JWT header or payload decoded before signature verification is untrusted.
This example targets the standard Cognito user-pool issuer and RS256 signing. If your pool uses another explicitly configured issuer/signing algorithm, adjust the allowlist and trusted configuration deliberately. Cache JWKS in production and refresh once on an unknown kid to handle rotation; never follow a token-supplied key URL. Verify any nonce you requested at sign-in, and any API-specific resource audience when using resource binding. Offline signature checks cannot detect token revocation or user disablement; enforce your API's revocation/session policy separately. M2M access tokens may not represent a user; this example validates user tokens.
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.
Chilkat AutoIt Downloads
Local $bSuccess = False
; Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = False
; App settings are trusted configuration. Keep a separate account_key/cache per local user.
$oApp = ObjCreate("Chilkat.JsonObject")
$oApp.Strict = True
$bSuccess = $oApp.LoadFile("qa_data/cognito/app.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not load Cognito app settings." & @CRLF)
Exit
EndIf
If (($oApp.JsonTypeOf("region") <> 1) Or ($oApp.StringOf("region") = "")) Then
ConsoleWrite("Missing or invalid region." & @CRLF)
Exit
EndIf
If (($oApp.JsonTypeOf("user_pool_id") <> 1) Or ($oApp.StringOf("user_pool_id") = "")) Then
ConsoleWrite("Missing or invalid user_pool_id." & @CRLF)
Exit
EndIf
If (($oApp.JsonTypeOf("client_id") <> 1) Or ($oApp.StringOf("client_id") = "")) Then
ConsoleWrite("Missing or invalid client_id." & @CRLF)
Exit
EndIf
If (($oApp.JsonTypeOf("account_key") <> 1) Or ($oApp.StringOf("account_key") = "")) Then
ConsoleWrite("Missing or invalid account_key." & @CRLF)
Exit
EndIf
Local $sClientId = $oApp.StringOf("client_id")
$oEndpoint = ObjCreate("Chilkat.StringBuilder")
$oEndpoint.Append("https://cognito-idp.")
$oEndpoint.Append($oApp.StringOf("region"))
$oEndpoint.Append(".amazonaws.com/")
$oHttp = ObjCreate("Chilkat.Http")
$oHttp.RequireSslCertVerify = True
$oHttp.FollowRedirects = False
$oHttp.ConnectTimeout = 20
$oHttp.ReadTimeout = 60
$oResp = ObjCreate("Chilkat.HttpResponse")
$oBody = ObjCreate("Chilkat.JsonObject")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
$oCached = ObjCreate("Chilkat.JsonObject")
$oCached.Strict = True
$bSuccess = $oCached.LoadFile("qa_data/tokens/cognito-user.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not load qa_data/tokens/cognito-user.json." & @CRLF)
Exit
EndIf
If (($oCached.JsonTypeOf("client_id") <> 1) Or ($oCached.StringOf("client_id") = "")) Then
ConsoleWrite("Missing or invalid client_id." & @CRLF)
Exit
EndIf
If ($oCached.StringOf("client_id") <> $oApp.StringOf("client_id")) Then
ConsoleWrite("Saved data belongs to another client, pool, or local account." & @CRLF)
Exit
EndIf
If (($oCached.JsonTypeOf("user_pool_id") <> 1) Or ($oCached.StringOf("user_pool_id") = "")) Then
ConsoleWrite("Missing or invalid user_pool_id." & @CRLF)
Exit
EndIf
If ($oCached.StringOf("user_pool_id") <> $oApp.StringOf("user_pool_id")) Then
ConsoleWrite("Saved data belongs to another client, pool, or local account." & @CRLF)
Exit
EndIf
If (($oCached.JsonTypeOf("account_key") <> 1) Or ($oCached.StringOf("account_key") = "")) Then
ConsoleWrite("Missing or invalid account_key." & @CRLF)
Exit
EndIf
If ($oCached.StringOf("account_key") <> $oApp.StringOf("account_key")) Then
ConsoleWrite("Saved data belongs to another client, pool, or local account." & @CRLF)
Exit
EndIf
; Choose the expected token type independently of the incoming JWT.
Local $sExpectedUse = "access"
Local $sRequiredScope = "aws.cognito.signin.user.admin"
If (($sExpectedUse <> "access") And ($sExpectedUse <> "id")) Then
ConsoleWrite("Choose access or id." & @CRLF)
Exit
EndIf
Local $sEncodedToken = $oCached.StringOf("access_token")
If ($sExpectedUse = "id") Then
$sEncodedToken = $oCached.StringOf("id_token")
EndIf
If ((($sExpectedUse = "access") And ($oCached.JsonTypeOf("access_token") <> 1)) Or (($sExpectedUse = "id") And ($oCached.JsonTypeOf("id_token") <> 1)) Or ($sEncodedToken = "")) Then
ConsoleWrite("Missing JWT." & @CRLF)
Exit
EndIf
$oJwt = ObjCreate("Chilkat.Jwt")
$oHeader = ObjCreate("Chilkat.JsonObject")
$oHeader.Strict = True
$bSuccess = $oHeader.Load($oJwt.GetHeader($sEncodedToken))
If ($bSuccess <> True) Then
ConsoleWrite("Invalid JWT header." & @CRLF)
Exit
EndIf
If ($oHeader.StringOf("alg") <> "RS256") Then
ConsoleWrite("Expected RS256; do not trust the token algorithm without an allowlist." & @CRLF)
Exit
EndIf
If (($oHeader.JsonTypeOf("kid") <> 1) Or ($oHeader.StringOf("kid") = "")) Then
ConsoleWrite("Missing or invalid kid." & @CRLF)
Exit
EndIf
$oIssuer = ObjCreate("Chilkat.StringBuilder")
$oIssuer.Append($oEndpoint.GetAsString())
$oIssuer.Append($oApp.StringOf("user_pool_id"))
$oJwksUrl = ObjCreate("Chilkat.StringBuilder")
$oJwksUrl.Append($oIssuer.GetAsString())
$oJwksUrl.Append("/.well-known/jwks.json")
; Use the configured issuer. Ignore jku/x5u URLs supplied in an untrusted JWT header.
$bSuccess = $oHttp.HttpNoBody("GET",$oJwksUrl.GetAsString(),$oResp)
If ($oResp.StatusCode <> 200) Then
ConsoleWrite("HTTP status: " & $oResp.StatusCode & @CRLF)
$bSuccess = $oResult.Load($oResp.BodyStr)
If ($bSuccess = True) Then
ConsoleWrite("Error type: " & $oResult.StringOf("__type") & @CRLF)
ConsoleWrite("OAuth error: " & $oResult.StringOf("error") & @CRLF)
EndIf
; Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
Exit
EndIf
If ($bSuccess <> True) Then
ConsoleWrite("The HTTP exchange did not complete." & @CRLF)
Exit
EndIf
$bSuccess = $oResult.Load($oResp.BodyStr)
If ($bSuccess <> True) Then
ConsoleWrite("Expected a JSON response." & @CRLF)
Exit
EndIf
If ($oResult.JsonTypeOf("keys") <> 4) Then
ConsoleWrite("Expected a JWKS keys array." & @CRLF)
Exit
EndIf
Local $i = 0
Local $iCount = $oResult.SizeOfArray("keys")
Local $iMatches = 0
$oJwk = ObjCreate("Chilkat.JsonObject")
While $i < $iCount
$oResult.I = $i
If ($oResult.StringOf("keys[i].kid") = $oHeader.StringOf("kid")) Then
$iMatches = $iMatches + 1
$bSuccess = $oResult.ObjectOf2("keys[i]",$oJwk)
If ($bSuccess <> True) Then
ConsoleWrite("Could not read the matching key." & @CRLF)
Exit
EndIf
EndIf
$i = $i + 1
Wend
If ($iMatches <> 1) Then
ConsoleWrite("Expected exactly one matching signing key." & @CRLF)
Exit
EndIf
If (($oJwk.StringOf("kty") <> "RSA") Or ($oJwk.StringOf("use") <> "sig") Or ($oJwk.StringOf("alg") <> "RS256")) Then
ConsoleWrite("Unexpected signing-key type, use, or algorithm." & @CRLF)
Exit
EndIf
$oPublicKey = ObjCreate("Chilkat.PublicKey")
$bSuccess = $oPublicKey.LoadFromString($oJwk.Emit())
If ($bSuccess <> True) Then
ConsoleWrite("Could not load the RSA JWK." & @CRLF)
Exit
EndIf
$bSuccess = $oJwt.VerifyJwtPk($sEncodedToken,$oPublicKey)
If ($bSuccess <> True) Then
ConsoleWrite("Invalid JWT signature." & @CRLF)
Exit
EndIf
; Only now inspect trusted claims. A valid signature alone is not sufficient.
$oClaims = ObjCreate("Chilkat.JsonObject")
$oClaims.Strict = True
$bSuccess = $oClaims.Load($oJwt.GetPayload($sEncodedToken))
If ($bSuccess <> True) Then
ConsoleWrite("Invalid JWT claims." & @CRLF)
Exit
EndIf
If ($oClaims.StringOf("iss") <> $oIssuer.GetAsString()) Then
ConsoleWrite("JWT issuer mismatch." & @CRLF)
Exit
EndIf
If ($oClaims.StringOf("token_use") <> $sExpectedUse) Then
ConsoleWrite("Wrong token purpose." & @CRLF)
Exit
EndIf
If (($oClaims.JsonTypeOf("exp") <> 2) Or ($oClaims.JsonTypeOf("iat") <> 2)) Then
ConsoleWrite("Missing numeric expiration or issue time." & @CRLF)
Exit
EndIf
If ($oJwt.IsTimeValid($sEncodedToken,60) <> True) Then
ConsoleWrite("JWT is expired or not yet valid." & @CRLF)
Exit
EndIf
If ($sExpectedUse = "id") Then
If ($oClaims.StringOf("aud") <> $sClientId) Then
ConsoleWrite("ID token audience mismatch." & @CRLF)
Exit
EndIf
Else
If ($oClaims.StringOf("client_id") <> $sClientId) Then
ConsoleWrite("Access token client mismatch." & @CRLF)
Exit
EndIf
; Whole-word scope matching, not a substring match.
$oScopes = ObjCreate("Chilkat.StringBuilder")
$oScopes.Append(" ")
$oScopes.Append($oClaims.StringOf("scope"))
$oScopes.Append(" ")
$oWantedScope = ObjCreate("Chilkat.StringBuilder")
$oWantedScope.Append(" ")
$oWantedScope.Append($sRequiredScope)
$oWantedScope.Append(" ")
If (($sRequiredScope <> "") And ($oScopes.Contains($oWantedScope.GetAsString(),True) <> True)) Then
ConsoleWrite("Required scope is absent." & @CRLF)
Exit
EndIf
EndIf
If (($oClaims.JsonTypeOf("sub") <> 1) Or ($oClaims.StringOf("sub") = "")) Then
ConsoleWrite("Missing or invalid sub." & @CRLF)
Exit
EndIf
ConsoleWrite("JWT signature and required claims are valid." & @CRLF)
; Apply your application's authorization policy before granting access.