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 VBScript Downloads
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create a Unicode (utf-16) output text file.
Set outFile = fso.CreateTextFile("output.txt", True, True)
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.
set app = CreateObject("Chilkat.JsonObject")
app.Strict = 1
success = app.LoadFile("qa_data/cognito/app.json")
If (success <> 1) Then
outFile.WriteLine("Could not load Cognito app settings.")
WScript.Quit
End If
If ((app.JsonTypeOf("region") <> 1) Or (app.StringOf("region") = "")) Then
outFile.WriteLine("Missing or invalid region.")
WScript.Quit
End If
If ((app.JsonTypeOf("user_pool_id") <> 1) Or (app.StringOf("user_pool_id") = "")) Then
outFile.WriteLine("Missing or invalid user_pool_id.")
WScript.Quit
End If
If ((app.JsonTypeOf("client_id") <> 1) Or (app.StringOf("client_id") = "")) Then
outFile.WriteLine("Missing or invalid client_id.")
WScript.Quit
End If
If ((app.JsonTypeOf("account_key") <> 1) Or (app.StringOf("account_key") = "")) Then
outFile.WriteLine("Missing or invalid account_key.")
WScript.Quit
End If
clientId = app.StringOf("client_id")
set endpoint = CreateObject("Chilkat.StringBuilder")
success = endpoint.Append("https://cognito-idp.")
success = endpoint.Append(app.StringOf("region"))
success = endpoint.Append(".amazonaws.com/")
set http = CreateObject("Chilkat.Http")
http.RequireSslCertVerify = 1
http.FollowRedirects = 0
http.ConnectTimeout = 20
http.ReadTimeout = 60
set resp = CreateObject("Chilkat.HttpResponse")
set body = CreateObject("Chilkat.JsonObject")
set result = CreateObject("Chilkat.JsonObject")
result.Strict = 1
set cached = CreateObject("Chilkat.JsonObject")
cached.Strict = 1
success = cached.LoadFile("qa_data/tokens/cognito-user.json")
If (success <> 1) Then
outFile.WriteLine("Could not load qa_data/tokens/cognito-user.json.")
WScript.Quit
End If
If ((cached.JsonTypeOf("client_id") <> 1) Or (cached.StringOf("client_id") = "")) Then
outFile.WriteLine("Missing or invalid client_id.")
WScript.Quit
End If
If (cached.StringOf("client_id") <> app.StringOf("client_id")) Then
outFile.WriteLine("Saved data belongs to another client, pool, or local account.")
WScript.Quit
End If
If ((cached.JsonTypeOf("user_pool_id") <> 1) Or (cached.StringOf("user_pool_id") = "")) Then
outFile.WriteLine("Missing or invalid user_pool_id.")
WScript.Quit
End If
If (cached.StringOf("user_pool_id") <> app.StringOf("user_pool_id")) Then
outFile.WriteLine("Saved data belongs to another client, pool, or local account.")
WScript.Quit
End If
If ((cached.JsonTypeOf("account_key") <> 1) Or (cached.StringOf("account_key") = "")) Then
outFile.WriteLine("Missing or invalid account_key.")
WScript.Quit
End If
If (cached.StringOf("account_key") <> app.StringOf("account_key")) Then
outFile.WriteLine("Saved data belongs to another client, pool, or local account.")
WScript.Quit
End If
' Choose the expected token type independently of the incoming JWT.
expectedUse = "access"
requiredScope = "aws.cognito.signin.user.admin"
If ((expectedUse <> "access") And (expectedUse <> "id")) Then
outFile.WriteLine("Choose access or id.")
WScript.Quit
End If
encodedToken = cached.StringOf("access_token")
If (expectedUse = "id") Then
encodedToken = cached.StringOf("id_token")
End If
If (((expectedUse = "access") And (cached.JsonTypeOf("access_token") <> 1)) Or ((expectedUse = "id") And (cached.JsonTypeOf("id_token") <> 1)) Or (encodedToken = "")) Then
outFile.WriteLine("Missing JWT.")
WScript.Quit
End If
set jwt = CreateObject("Chilkat.Jwt")
set header = CreateObject("Chilkat.JsonObject")
header.Strict = 1
success = header.Load(jwt.GetHeader(encodedToken))
If (success <> 1) Then
outFile.WriteLine("Invalid JWT header.")
WScript.Quit
End If
If (header.StringOf("alg") <> "RS256") Then
outFile.WriteLine("Expected RS256; do not trust the token algorithm without an allowlist.")
WScript.Quit
End If
If ((header.JsonTypeOf("kid") <> 1) Or (header.StringOf("kid") = "")) Then
outFile.WriteLine("Missing or invalid kid.")
WScript.Quit
End If
set issuer = CreateObject("Chilkat.StringBuilder")
success = issuer.Append(endpoint.GetAsString())
success = issuer.Append(app.StringOf("user_pool_id"))
set jwksUrl = CreateObject("Chilkat.StringBuilder")
success = jwksUrl.Append(issuer.GetAsString())
success = 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 <> 200) Then
outFile.WriteLine("HTTP status: " & resp.StatusCode)
success = result.Load(resp.BodyStr)
If (success = 1) Then
outFile.WriteLine("Error type: " & result.StringOf("__type"))
outFile.WriteLine("OAuth error: " & result.StringOf("error"))
End If
' Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
WScript.Quit
End If
If (success <> 1) Then
outFile.WriteLine("The HTTP exchange did not complete.")
WScript.Quit
End If
success = result.Load(resp.BodyStr)
If (success <> 1) Then
outFile.WriteLine("Expected a JSON response.")
WScript.Quit
End If
If (result.JsonTypeOf("keys") <> 4) Then
outFile.WriteLine("Expected a JWKS keys array.")
WScript.Quit
End If
i = 0
count = result.SizeOfArray("keys")
matches = 0
set jwk = CreateObject("Chilkat.JsonObject")
Do While i < count
result.I = i
If (result.StringOf("keys[i].kid") = header.StringOf("kid")) Then
matches = matches + 1
success = result.ObjectOf2("keys[i]",jwk)
If (success <> 1) Then
outFile.WriteLine("Could not read the matching key.")
WScript.Quit
End If
End If
i = i + 1
Loop
If (matches <> 1) Then
outFile.WriteLine("Expected exactly one matching signing key.")
WScript.Quit
End If
If ((jwk.StringOf("kty") <> "RSA") Or (jwk.StringOf("use") <> "sig") Or (jwk.StringOf("alg") <> "RS256")) Then
outFile.WriteLine("Unexpected signing-key type, use, or algorithm.")
WScript.Quit
End If
set publicKey = CreateObject("Chilkat.PublicKey")
success = publicKey.LoadFromString(jwk.Emit())
If (success <> 1) Then
outFile.WriteLine("Could not load the RSA JWK.")
WScript.Quit
End If
success = jwt.VerifyJwtPk(encodedToken,publicKey)
If (success <> 1) Then
outFile.WriteLine("Invalid JWT signature.")
WScript.Quit
End If
' Only now inspect trusted claims. A valid signature alone is not sufficient.
set claims = CreateObject("Chilkat.JsonObject")
claims.Strict = 1
success = claims.Load(jwt.GetPayload(encodedToken))
If (success <> 1) Then
outFile.WriteLine("Invalid JWT claims.")
WScript.Quit
End If
If (claims.StringOf("iss") <> issuer.GetAsString()) Then
outFile.WriteLine("JWT issuer mismatch.")
WScript.Quit
End If
If (claims.StringOf("token_use") <> expectedUse) Then
outFile.WriteLine("Wrong token purpose.")
WScript.Quit
End If
If ((claims.JsonTypeOf("exp") <> 2) Or (claims.JsonTypeOf("iat") <> 2)) Then
outFile.WriteLine("Missing numeric expiration or issue time.")
WScript.Quit
End If
If (jwt.IsTimeValid(encodedToken,60) <> 1) Then
outFile.WriteLine("JWT is expired or not yet valid.")
WScript.Quit
End If
If (expectedUse = "id") Then
If (claims.StringOf("aud") <> clientId) Then
outFile.WriteLine("ID token audience mismatch.")
WScript.Quit
End If
Else
If (claims.StringOf("client_id") <> clientId) Then
outFile.WriteLine("Access token client mismatch.")
WScript.Quit
End If
' Whole-word scope matching, not a substring match.
set scopes = CreateObject("Chilkat.StringBuilder")
success = scopes.Append(" ")
success = scopes.Append(claims.StringOf("scope"))
success = scopes.Append(" ")
set wantedScope = CreateObject("Chilkat.StringBuilder")
success = wantedScope.Append(" ")
success = wantedScope.Append(requiredScope)
success = wantedScope.Append(" ")
If ((requiredScope <> "") And (scopes.Contains(wantedScope.GetAsString(),1) <> 1)) Then
outFile.WriteLine("Required scope is absent.")
WScript.Quit
End If
End If
If ((claims.JsonTypeOf("sub") <> 1) Or (claims.StringOf("sub") = "")) Then
outFile.WriteLine("Missing or invalid sub.")
WScript.Quit
End If
outFile.WriteLine("JWT signature and required claims are valid.")
' Apply your application's authorization policy before granting access.
outFile.Close