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 Go Downloads
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 := chilkat.NewJsonObject()
app.SetStrict(true)
success = app.LoadFile("qa_data/cognito/app.json")
if success != true {
fmt.Println("Could not load Cognito app settings.")
app.DisposeJsonObject()
return
}
if (app.JsonTypeOf("region") != 1) || (app.StringOf("region") == "") {
fmt.Println("Missing or invalid region.")
app.DisposeJsonObject()
return
}
if (app.JsonTypeOf("user_pool_id") != 1) || (app.StringOf("user_pool_id") == "") {
fmt.Println("Missing or invalid user_pool_id.")
app.DisposeJsonObject()
return
}
if (app.JsonTypeOf("client_id") != 1) || (app.StringOf("client_id") == "") {
fmt.Println("Missing or invalid client_id.")
app.DisposeJsonObject()
return
}
if (app.JsonTypeOf("account_key") != 1) || (app.StringOf("account_key") == "") {
fmt.Println("Missing or invalid account_key.")
app.DisposeJsonObject()
return
}
clientId := app.StringOf("client_id")
endpoint := chilkat.NewStringBuilder()
endpoint.Append("https://cognito-idp.")
endpoint.Append(*app.StringOf("region"))
endpoint.Append(".amazonaws.com/")
http := chilkat.NewHttp()
http.SetRequireSslCertVerify(true)
http.SetFollowRedirects(false)
http.SetConnectTimeout(20)
http.SetReadTimeout(60)
resp := chilkat.NewHttpResponse()
body := chilkat.NewJsonObject()
result := chilkat.NewJsonObject()
result.SetStrict(true)
cached := chilkat.NewJsonObject()
cached.SetStrict(true)
success = cached.LoadFile("qa_data/tokens/cognito-user.json")
if success != true {
fmt.Println("Could not load qa_data/tokens/cognito-user.json.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
return
}
if (cached.JsonTypeOf("client_id") != 1) || (cached.StringOf("client_id") == "") {
fmt.Println("Missing or invalid client_id.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
return
}
if cached.StringOf("client_id") != app.StringOf("client_id") {
fmt.Println("Saved data belongs to another client, pool, or local account.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
return
}
if (cached.JsonTypeOf("user_pool_id") != 1) || (cached.StringOf("user_pool_id") == "") {
fmt.Println("Missing or invalid user_pool_id.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
return
}
if cached.StringOf("user_pool_id") != app.StringOf("user_pool_id") {
fmt.Println("Saved data belongs to another client, pool, or local account.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
return
}
if (cached.JsonTypeOf("account_key") != 1) || (cached.StringOf("account_key") == "") {
fmt.Println("Missing or invalid account_key.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
return
}
if cached.StringOf("account_key") != app.StringOf("account_key") {
fmt.Println("Saved data belongs to another client, pool, or local account.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
return
}
// Choose the expected token type independently of the incoming JWT.
expectedUse := "access"
requiredScope := "aws.cognito.signin.user.admin"
if (expectedUse != "access") && (expectedUse != "id") {
fmt.Println("Choose access or id.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
return
}
encodedToken := cached.StringOf("access_token")
if expectedUse == "id" {
encodedToken = cached.StringOf("id_token")
}
if ((expectedUse == "access") && (cached.JsonTypeOf("access_token") != 1)) || ((expectedUse == "id") && (cached.JsonTypeOf("id_token") != 1)) || (*encodedToken == "") {
fmt.Println("Missing JWT.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
return
}
jwt := chilkat.NewJwt()
header := chilkat.NewJsonObject()
header.SetStrict(true)
success = header.Load(*jwt.GetHeader(*encodedToken))
if success != true {
fmt.Println("Invalid JWT header.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
return
}
if header.StringOf("alg") != "RS256" {
fmt.Println("Expected RS256; do not trust the token algorithm without an allowlist.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
return
}
if (header.JsonTypeOf("kid") != 1) || (header.StringOf("kid") == "") {
fmt.Println("Missing or invalid kid.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
return
}
issuer := chilkat.NewStringBuilder()
issuer.Append(*endpoint.GetAsString())
issuer.Append(*app.StringOf("user_pool_id"))
jwksUrl := chilkat.NewStringBuilder()
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 {
fmt.Println("HTTP status: ", resp.StatusCode())
success = result.Load(resp.BodyStr())
if success == true {
fmt.Println("Error type: ", *result.StringOf("__type"))
fmt.Println("OAuth error: ", *result.StringOf("error"))
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
return
}
if success != true {
fmt.Println("The HTTP exchange did not complete.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
return
}
success = result.Load(resp.BodyStr())
if success != true {
fmt.Println("Expected a JSON response.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
return
}
if result.JsonTypeOf("keys") != 4 {
fmt.Println("Expected a JWKS keys array.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
return
}
i := 0
count := result.SizeOfArray("keys")
matches := 0
jwk := chilkat.NewJsonObject()
for i < count {
result.SetI(i)
if result.StringOf("keys[i].kid") == header.StringOf("kid") {
matches = matches + 1
success = result.ObjectOf2("keys[i]",jwk)
if success != true {
fmt.Println("Could not read the matching key.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
return
}
}
i = i + 1
}
if matches != 1 {
fmt.Println("Expected exactly one matching signing key.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
return
}
if (jwk.StringOf("kty") != "RSA") || (jwk.StringOf("use") != "sig") || (jwk.StringOf("alg") != "RS256") {
fmt.Println("Unexpected signing-key type, use, or algorithm.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
return
}
publicKey := chilkat.NewPublicKey()
success = publicKey.LoadFromString(*jwk.Emit())
if success != true {
fmt.Println("Could not load the RSA JWK.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
publicKey.DisposePublicKey()
return
}
success = jwt.VerifyJwtPk(*encodedToken,publicKey)
if success != true {
fmt.Println("Invalid JWT signature.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
publicKey.DisposePublicKey()
return
}
// Only now inspect trusted claims. A valid signature alone is not sufficient.
claims := chilkat.NewJsonObject()
claims.SetStrict(true)
success = claims.Load(*jwt.GetPayload(*encodedToken))
if success != true {
fmt.Println("Invalid JWT claims.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
publicKey.DisposePublicKey()
claims.DisposeJsonObject()
return
}
if claims.StringOf("iss") != issuer.GetAsString() {
fmt.Println("JWT issuer mismatch.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
publicKey.DisposePublicKey()
claims.DisposeJsonObject()
return
}
if claims.StringOf("token_use") != expectedUse {
fmt.Println("Wrong token purpose.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
publicKey.DisposePublicKey()
claims.DisposeJsonObject()
return
}
if (claims.JsonTypeOf("exp") != 2) || (claims.JsonTypeOf("iat") != 2) {
fmt.Println("Missing numeric expiration or issue time.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
publicKey.DisposePublicKey()
claims.DisposeJsonObject()
return
}
if jwt.IsTimeValid(*encodedToken,60) != true {
fmt.Println("JWT is expired or not yet valid.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
publicKey.DisposePublicKey()
claims.DisposeJsonObject()
return
}
if expectedUse == "id" {
if claims.StringOf("aud") != *clientId {
fmt.Println("ID token audience mismatch.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
publicKey.DisposePublicKey()
claims.DisposeJsonObject()
return
}
} else {
if claims.StringOf("client_id") != *clientId {
fmt.Println("Access token client mismatch.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
publicKey.DisposePublicKey()
claims.DisposeJsonObject()
return
}
// Whole-word scope matching, not a substring match.
scopes := chilkat.NewStringBuilder()
scopes.Append(" ")
scopes.Append(*claims.StringOf("scope"))
scopes.Append(" ")
wantedScope := chilkat.NewStringBuilder()
wantedScope.Append(" ")
wantedScope.Append(requiredScope)
wantedScope.Append(" ")
if (requiredScope != "") && (scopes.Contains(*wantedScope.GetAsString(),true) != true) {
fmt.Println("Required scope is absent.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
publicKey.DisposePublicKey()
claims.DisposeJsonObject()
scopes.DisposeStringBuilder()
wantedScope.DisposeStringBuilder()
return
}
}
if (claims.JsonTypeOf("sub") != 1) || (claims.StringOf("sub") == "") {
fmt.Println("Missing or invalid sub.")
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
publicKey.DisposePublicKey()
claims.DisposeJsonObject()
scopes.DisposeStringBuilder()
wantedScope.DisposeStringBuilder()
return
}
fmt.Println("JWT signature and required claims are valid.")
// Apply your application's authorization policy before granting access.
app.DisposeJsonObject()
endpoint.DisposeStringBuilder()
http.DisposeHttp()
resp.DisposeHttpResponse()
body.DisposeJsonObject()
result.DisposeJsonObject()
cached.DisposeJsonObject()
jwt.DisposeJwt()
header.DisposeJsonObject()
issuer.DisposeStringBuilder()
jwksUrl.DisposeStringBuilder()
jwk.DisposeJsonObject()
publicKey.DisposePublicKey()
claims.DisposeJsonObject()
scopes.DisposeStringBuilder()
wantedScope.DisposeStringBuilder()