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 Swift Downloads
func chilkatTest() {
var success: Bool = 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.
let app = CkoJsonObject()!
app.strict = true
success = app.loadFile(path: "qa_data/cognito/app.json")
if success != true {
print("Could not load Cognito app settings.")
return
}
if (app.jsonType(of: "region").intValue != 1) || (app.string(of: "region") == "") {
print("Missing or invalid region.")
return
}
if (app.jsonType(of: "user_pool_id").intValue != 1) || (app.string(of: "user_pool_id") == "") {
print("Missing or invalid user_pool_id.")
return
}
if (app.jsonType(of: "client_id").intValue != 1) || (app.string(of: "client_id") == "") {
print("Missing or invalid client_id.")
return
}
if (app.jsonType(of: "account_key").intValue != 1) || (app.string(of: "account_key") == "") {
print("Missing or invalid account_key.")
return
}
var clientId: String? = app.string(of: "client_id")
let endpoint = CkoStringBuilder()!
endpoint.append(value: "https://cognito-idp.")
endpoint.append(value: app.string(of: "region"))
endpoint.append(value: ".amazonaws.com/")
let http = CkoHttp()!
http.requireSslCertVerify = true
http.followRedirects = false
http.connectTimeout = 20
http.readTimeout = 60
let resp = CkoHttpResponse()!
let body = CkoJsonObject()!
let result = CkoJsonObject()!
result.strict = true
let cached = CkoJsonObject()!
cached.strict = true
success = cached.loadFile(path: "qa_data/tokens/cognito-user.json")
if success != true {
print("Could not load qa_data/tokens/cognito-user.json.")
return
}
if (cached.jsonType(of: "client_id").intValue != 1) || (cached.string(of: "client_id") == "") {
print("Missing or invalid client_id.")
return
}
if cached.string(of: "client_id") != app.string(of: "client_id") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if (cached.jsonType(of: "user_pool_id").intValue != 1) || (cached.string(of: "user_pool_id") == "") {
print("Missing or invalid user_pool_id.")
return
}
if cached.string(of: "user_pool_id") != app.string(of: "user_pool_id") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if (cached.jsonType(of: "account_key").intValue != 1) || (cached.string(of: "account_key") == "") {
print("Missing or invalid account_key.")
return
}
if cached.string(of: "account_key") != app.string(of: "account_key") {
print("Saved data belongs to another client, pool, or local account.")
return
}
// Choose the expected token type independently of the incoming JWT.
var expectedUse: String? = "access"
var requiredScope: String? = "aws.cognito.signin.user.admin"
if (expectedUse != "access") && (expectedUse != "id") {
print("Choose access or id.")
return
}
var encodedToken: String? = cached.string(of: "access_token")
if expectedUse == "id" {
encodedToken = cached.string(of: "id_token")
}
if ((expectedUse == "access") && (cached.jsonType(of: "access_token").intValue != 1)) || ((expectedUse == "id") && (cached.jsonType(of: "id_token").intValue != 1)) || (encodedToken == "") {
print("Missing JWT.")
return
}
let jwt = CkoJwt()!
let header = CkoJsonObject()!
header.strict = true
success = header.load(json: jwt.getHeader(token: encodedToken))
if success != true {
print("Invalid JWT header.")
return
}
if header.string(of: "alg") != "RS256" {
print("Expected RS256; do not trust the token algorithm without an allowlist.")
return
}
if (header.jsonType(of: "kid").intValue != 1) || (header.string(of: "kid") == "") {
print("Missing or invalid kid.")
return
}
let issuer = CkoStringBuilder()!
issuer.append(value: endpoint.getAsString())
issuer.append(value: app.string(of: "user_pool_id"))
let jwksUrl = CkoStringBuilder()!
jwksUrl.append(value: issuer.getAsString())
jwksUrl.append(value: "/.well-known/jwks.json")
// Use the configured issuer. Ignore jku/x5u URLs supplied in an untrusted JWT header.
success = http.httpNoBody(verb: "GET", url: jwksUrl.getAsString(), response: resp)
if resp.statusCode.intValue != 200 {
print("HTTP status: \(resp.statusCode.intValue)")
success = result.load(json: resp.bodyStr)
if success == true {
print("Error type: \(result.string(of: "__type")!)")
print("OAuth error: \(result.string(of: "error")!)")
}
// Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
return
}
if success != true {
print("The HTTP exchange did not complete.")
return
}
success = result.load(json: resp.bodyStr)
if success != true {
print("Expected a JSON response.")
return
}
if result.jsonType(of: "keys").intValue != 4 {
print("Expected a JWKS keys array.")
return
}
var i: Int = 0
var count: Int = result.size(ofArray: "keys").intValue
var matches: Int = 0
let jwk = CkoJsonObject()!
while i < count {
result.i = i
if result.string(of: "keys[i].kid") == header.string(of: "kid") {
matches = matches + 1
success = result.objectOf2(jsonPath: "keys[i]", jsonObj: jwk)
if success != true {
print("Could not read the matching key.")
return
}
}
i = i + 1
}
if matches != 1 {
print("Expected exactly one matching signing key.")
return
}
if (jwk.string(of: "kty") != "RSA") || (jwk.string(of: "use") != "sig") || (jwk.string(of: "alg") != "RS256") {
print("Unexpected signing-key type, use, or algorithm.")
return
}
let publicKey = CkoPublicKey()!
success = publicKey.load(fromString: jwk.emit())
if success != true {
print("Could not load the RSA JWK.")
return
}
success = jwt.verifyPk(token: encodedToken, key: publicKey)
if success != true {
print("Invalid JWT signature.")
return
}
// Only now inspect trusted claims. A valid signature alone is not sufficient.
let claims = CkoJsonObject()!
claims.strict = true
success = claims.load(json: jwt.getPayload(token: encodedToken))
if success != true {
print("Invalid JWT claims.")
return
}
if claims.string(of: "iss") != issuer.getAsString() {
print("JWT issuer mismatch.")
return
}
if claims.string(of: "token_use") != expectedUse {
print("Wrong token purpose.")
return
}
if (claims.jsonType(of: "exp").intValue != 2) || (claims.jsonType(of: "iat").intValue != 2) {
print("Missing numeric expiration or issue time.")
return
}
if jwt.isTimeValid(jwt: encodedToken, leeway: 60) != true {
print("JWT is expired or not yet valid.")
return
}
if expectedUse == "id" {
if claims.string(of: "aud") != clientId {
print("ID token audience mismatch.")
return
}
}
else {
if claims.string(of: "client_id") != clientId {
print("Access token client mismatch.")
return
}
// Whole-word scope matching, not a substring match.
let scopes = CkoStringBuilder()!
scopes.append(value: " ")
scopes.append(value: claims.string(of: "scope"))
scopes.append(value: " ")
let wantedScope = CkoStringBuilder()!
wantedScope.append(value: " ")
wantedScope.append(value: requiredScope)
wantedScope.append(value: " ")
if (requiredScope != "") && (scopes.contains(str: wantedScope.getAsString(), caseSensitive: true) != true) {
print("Required scope is absent.")
return
}
}
if (claims.jsonType(of: "sub").intValue != 1) || (claims.string(of: "sub") == "") {
print("Missing or invalid sub.")
return
}
print("JWT signature and required claims are valid.")
// Apply your application's authorization policy before granting access.
}