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

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.

AWS documentation 1

Chilkat B4X Downloads

B4X
Dim success As Boolean = 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.
Dim app As ChilkatJsonObject
app.Initialize
app.Strict = True
success = app.LoadFile("qa_data/cognito/app.json")
If success <> True Then
    Log("Could not load Cognito app settings.")
    Return
End If

If (app.JsonTypeOf("region") <> 1) Or (app.StringOf("region") = "") Then
    Log("Missing or invalid region.")
    Return
End If

If (app.JsonTypeOf("user_pool_id") <> 1) Or (app.StringOf("user_pool_id") = "") Then
    Log("Missing or invalid user_pool_id.")
    Return
End If

If (app.JsonTypeOf("client_id") <> 1) Or (app.StringOf("client_id") = "") Then
    Log("Missing or invalid client_id.")
    Return
End If

If (app.JsonTypeOf("account_key") <> 1) Or (app.StringOf("account_key") = "") Then
    Log("Missing or invalid account_key.")
    Return
End If

Dim clientId As String = app.StringOf("client_id")
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("https://cognito-idp.")
endpoint.Append(app.StringOf("region"))
endpoint.Append(".amazonaws.com/")
Dim http As ChilkatHttp
http.Initialize("http")
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 20
http.ReadTimeout = 60
Dim resp As ChilkatHttpResponse
resp.Initialize
Dim body As ChilkatJsonObject
body.Initialize
Dim result As ChilkatJsonObject
result.Initialize
result.Strict = True
Dim cached As ChilkatJsonObject
cached.Initialize
cached.Strict = True
success = cached.LoadFile("qa_data/tokens/cognito-user.json")
If success <> True Then
    Log("Could not load qa_data/tokens/cognito-user.json.")
    Return
End If

If (cached.JsonTypeOf("client_id") <> 1) Or (cached.StringOf("client_id") = "") Then
    Log("Missing or invalid client_id.")
    Return
End If

If cached.StringOf("client_id") <> app.StringOf("client_id") Then
    Log("Saved data belongs to another client, pool, or local account.")
    Return
End If

If (cached.JsonTypeOf("user_pool_id") <> 1) Or (cached.StringOf("user_pool_id") = "") Then
    Log("Missing or invalid user_pool_id.")
    Return
End If

If cached.StringOf("user_pool_id") <> app.StringOf("user_pool_id") Then
    Log("Saved data belongs to another client, pool, or local account.")
    Return
End If

If (cached.JsonTypeOf("account_key") <> 1) Or (cached.StringOf("account_key") = "") Then
    Log("Missing or invalid account_key.")
    Return
End If

If cached.StringOf("account_key") <> app.StringOf("account_key") Then
    Log("Saved data belongs to another client, pool, or local account.")
    Return
End If

'  Choose the expected token type independently of the incoming JWT.
Dim expectedUse As String = "access"
Dim requiredScope As String = "aws.cognito.signin.user.admin"
If (expectedUse <> "access") And (expectedUse <> "id") Then
    Log("Choose access or id.")
    Return
End If

Dim encodedToken As String = 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
    Log("Missing JWT.")
    Return
End If

Dim jwt As ChilkatJwt
jwt.Initialize
Dim header As ChilkatJsonObject
header.Initialize
header.Strict = True
success = header.Load(jwt.GetHeader(encodedToken))
If success <> True Then
    Log("Invalid JWT header.")
    Return
End If

If header.StringOf("alg") <> "RS256" Then
    Log("Expected RS256; do not trust the token algorithm without an allowlist.")
    Return
End If

If (header.JsonTypeOf("kid") <> 1) Or (header.StringOf("kid") = "") Then
    Log("Missing or invalid kid.")
    Return
End If

Dim issuer As ChilkatStringBuilder
issuer.Initialize
issuer.Append(endpoint.GetAsString)
issuer.Append(app.StringOf("user_pool_id"))
Dim jwksUrl As ChilkatStringBuilder
jwksUrl.Initialize
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 <> 200 Then
    Log("HTTP status: " & resp.StatusCode)
    success = result.Load(resp.BodyStr)
    If success = True Then
        Log("Error type: " & result.StringOf("__type"))
        Log("OAuth error: " & result.StringOf("error"))
    End If

    '  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    Return
End If

If success <> True Then
    Log("The HTTP exchange did not complete.")
    Return
End If

success = result.Load(resp.BodyStr)
If success <> True Then
    Log("Expected a JSON response.")
    Return
End If

If result.JsonTypeOf("keys") <> 4 Then
    Log("Expected a JWKS keys array.")
    Return
End If

Dim i As Int = 0
Dim count As Int = result.SizeOfArray("keys")
Dim matches As Int = 0
Dim jwk As ChilkatJsonObject
jwk.Initialize
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 <> True Then
            Log("Could not read the matching key.")
            Return
        End If

    End If

    i = i + 1
Loop
If matches <> 1 Then
    Log("Expected exactly one matching signing key.")
    Return
End If

If (jwk.StringOf("kty") <> "RSA") Or (jwk.StringOf("use") <> "sig") Or (jwk.StringOf("alg") <> "RS256") Then
    Log("Unexpected signing-key type, use, or algorithm.")
    Return
End If

Dim publicKey As ChilkatPublicKey
publicKey.Initialize
success = publicKey.LoadFromString(jwk.Emit)
If success <> True Then
    Log("Could not load the RSA JWK.")
    Return
End If

success = jwt.VerifyJwtPk(encodedToken, publicKey)
If success <> True Then
    Log("Invalid JWT signature.")
    Return
End If

'  Only now inspect trusted claims. A valid signature alone is not sufficient.
Dim claims As ChilkatJsonObject
claims.Initialize
claims.Strict = True
success = claims.Load(jwt.GetPayload(encodedToken))
If success <> True Then
    Log("Invalid JWT claims.")
    Return
End If

If claims.StringOf("iss") <> issuer.GetAsString Then
    Log("JWT issuer mismatch.")
    Return
End If

If claims.StringOf("token_use") <> expectedUse Then
    Log("Wrong token purpose.")
    Return
End If

If (claims.JsonTypeOf("exp") <> 2) Or (claims.JsonTypeOf("iat") <> 2) Then
    Log("Missing numeric expiration or issue time.")
    Return
End If

If jwt.IsTimeValid(encodedToken, 60) <> True Then
    Log("JWT is expired or not yet valid.")
    Return
End If

If expectedUse = "id" Then
    If claims.StringOf("aud") <> clientId Then
        Log("ID token audience mismatch.")
        Return
    End If

Else
    If claims.StringOf("client_id") <> clientId Then
        Log("Access token client mismatch.")
        Return
    End If

    '  Whole-word scope matching, not a substring match.
    Dim scopes As ChilkatStringBuilder
    scopes.Initialize
    scopes.Append(" ")
    scopes.Append(claims.StringOf("scope"))
    scopes.Append(" ")
    Dim wantedScope As ChilkatStringBuilder
    wantedScope.Initialize
    wantedScope.Append(" ")
    wantedScope.Append(requiredScope)
    wantedScope.Append(" ")
    If (requiredScope <> "") And (scopes.Contains(wantedScope.GetAsString, True) <> True) Then
        Log("Required scope is absent.")
        Return
    End If

End If

If (claims.JsonTypeOf("sub") <> 1) Or (claims.StringOf("sub") = "") Then
    Log("Missing or invalid sub.")
    Return
End If

Log("JWT signature and required claims are valid.")
'  Apply your application's authorization policy before granting access.