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 PowerShell Downloads
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/")
$http = New-Object Chilkat.Http
$http.RequireSslCertVerify = $true
$http.FollowRedirects = $false
$http.ConnectTimeout = 20
$http.ReadTimeout = 60
$resp = New-Object Chilkat.HttpResponse
$body = New-Object Chilkat.JsonObject
$result = New-Object Chilkat.JsonObject
$result.Strict = $true
$cached = New-Object Chilkat.JsonObject
$cached.Strict = $true
$success = $cached.LoadFile("qa_data/tokens/cognito-user.json")
if ($success -ne $true) {
$("Could not load qa_data/tokens/cognito-user.json.")
exit
}
if (($cached.JsonTypeOf("client_id") -ne 1) -or ($cached.StringOf("client_id") -eq "")) {
$("Missing or invalid client_id.")
exit
}
if ($cached.StringOf("client_id") -ne $app.StringOf("client_id")) {
$("Saved data belongs to another client, pool, or local account.")
exit
}
if (($cached.JsonTypeOf("user_pool_id") -ne 1) -or ($cached.StringOf("user_pool_id") -eq "")) {
$("Missing or invalid user_pool_id.")
exit
}
if ($cached.StringOf("user_pool_id") -ne $app.StringOf("user_pool_id")) {
$("Saved data belongs to another client, pool, or local account.")
exit
}
if (($cached.JsonTypeOf("account_key") -ne 1) -or ($cached.StringOf("account_key") -eq "")) {
$("Missing or invalid account_key.")
exit
}
if ($cached.StringOf("account_key") -ne $app.StringOf("account_key")) {
$("Saved data belongs to another client, pool, or local account.")
exit
}
# Choose the expected token type independently of the incoming JWT.
$expectedUse = "access"
$requiredScope = "aws.cognito.signin.user.admin"
if (($expectedUse -ne "access") -and ($expectedUse -ne "id")) {
$("Choose access or id.")
exit
}
$encodedToken = $cached.StringOf("access_token")
if ($expectedUse -eq "id") {
$encodedToken = $cached.StringOf("id_token")
}
if ((($expectedUse -eq "access") -and ($cached.JsonTypeOf("access_token") -ne 1)) -or (($expectedUse -eq "id") -and ($cached.JsonTypeOf("id_token") -ne 1)) -or ($encodedToken -eq "")) {
$("Missing JWT.")
exit
}
$jwt = New-Object Chilkat.Jwt
$header = New-Object Chilkat.JsonObject
$header.Strict = $true
$success = $header.Load($jwt.GetHeader($encodedToken))
if ($success -ne $true) {
$("Invalid JWT header.")
exit
}
if ($header.StringOf("alg") -ne "RS256") {
$("Expected RS256; do not trust the token algorithm without an allowlist.")
exit
}
if (($header.JsonTypeOf("kid") -ne 1) -or ($header.StringOf("kid") -eq "")) {
$("Missing or invalid kid.")
exit
}
$issuer = New-Object Chilkat.StringBuilder
$issuer.Append($endpoint.GetAsString())
$issuer.Append($app.StringOf("user_pool_id"))
$jwksUrl = New-Object Chilkat.StringBuilder
$jwksUrl.Append($issuer.GetAsString())
$jwksUrl.Append("/.well-known/jwks.json")
# Use the configured issuer. Ignore jku/x5u URLs supplied in an untrusted JWT header.
$success = $http.HttpNoBody("GET",$jwksUrl.GetAsString(),$resp)
if ($resp.StatusCode -ne 200) {
$("HTTP status: " + $resp.StatusCode)
$success = $result.Load($resp.BodyStr)
if ($success -eq $true) {
$("Error type: " + $result.StringOf("__type"))
$("OAuth error: " + $result.StringOf("error"))
}
# Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
exit
}
if ($success -ne $true) {
$("The HTTP exchange did not complete.")
exit
}
$success = $result.Load($resp.BodyStr)
if ($success -ne $true) {
$("Expected a JSON response.")
exit
}
if ($result.JsonTypeOf("keys") -ne 4) {
$("Expected a JWKS keys array.")
exit
}
$i = 0
$count = $result.SizeOfArray("keys")
$matches = 0
$jwk = New-Object Chilkat.JsonObject
while ($i -lt $count) {
$result.I = $i
if ($result.StringOf("keys[i].kid") -eq $header.StringOf("kid")) {
$matches = $matches + 1
$success = $result.ObjectOf2("keys[i]",$jwk)
if ($success -ne $true) {
$("Could not read the matching key.")
exit
}
}
$i = $i + 1
}
if ($matches -ne 1) {
$("Expected exactly one matching signing key.")
exit
}
if (($jwk.StringOf("kty") -ne "RSA") -or ($jwk.StringOf("use") -ne "sig") -or ($jwk.StringOf("alg") -ne "RS256")) {
$("Unexpected signing-key type, use, or algorithm.")
exit
}
$publicKey = New-Object Chilkat.PublicKey
$success = $publicKey.LoadFromString($jwk.Emit())
if ($success -ne $true) {
$("Could not load the RSA JWK.")
exit
}
$success = $jwt.VerifyJwtPk($encodedToken,$publicKey)
if ($success -ne $true) {
$("Invalid JWT signature.")
exit
}
# Only now inspect trusted claims. A valid signature alone is not sufficient.
$claims = New-Object Chilkat.JsonObject
$claims.Strict = $true
$success = $claims.Load($jwt.GetPayload($encodedToken))
if ($success -ne $true) {
$("Invalid JWT claims.")
exit
}
if ($claims.StringOf("iss") -ne $issuer.GetAsString()) {
$("JWT issuer mismatch.")
exit
}
if ($claims.StringOf("token_use") -ne $expectedUse) {
$("Wrong token purpose.")
exit
}
if (($claims.JsonTypeOf("exp") -ne 2) -or ($claims.JsonTypeOf("iat") -ne 2)) {
$("Missing numeric expiration or issue time.")
exit
}
if ($jwt.IsTimeValid($encodedToken,60) -ne $true) {
$("JWT is expired or not yet valid.")
exit
}
if ($expectedUse -eq "id") {
if ($claims.StringOf("aud") -ne $clientId) {
$("ID token audience mismatch.")
exit
}
}
else {
if ($claims.StringOf("client_id") -ne $clientId) {
$("Access token client mismatch.")
exit
}
# Whole-word scope matching, not a substring match.
$scopes = New-Object Chilkat.StringBuilder
$scopes.Append(" ")
$scopes.Append($claims.StringOf("scope"))
$scopes.Append(" ")
$wantedScope = New-Object Chilkat.StringBuilder
$wantedScope.Append(" ")
$wantedScope.Append($requiredScope)
$wantedScope.Append(" ")
if (($requiredScope -ne "") -and ($scopes.Contains($wantedScope.GetAsString(),$true) -ne $true)) {
$("Required scope is absent.")
exit
}
}
if (($claims.JsonTypeOf("sub") -ne 1) -or ($claims.StringOf("sub") -eq "")) {
$("Missing or invalid sub.")
exit
}
$("JWT signature and required claims are valid.")
# Apply your application's authorization policy before granting access.