Sample code for 30+ languages & platforms
C# 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 C# Downloads

C#
bool 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.
Chilkat.JsonObject app = new Chilkat.JsonObject();
app.Strict = true;
success = app.LoadFile("qa_data/cognito/app.json");
if (success != true) {
    Debug.WriteLine("Could not load Cognito app settings.");
    return;
}

if ((app.JsonTypeOf("region") != 1) || (app.StringOf("region") == "")) {
    Debug.WriteLine("Missing or invalid region.");
    return;
}

if ((app.JsonTypeOf("user_pool_id") != 1) || (app.StringOf("user_pool_id") == "")) {
    Debug.WriteLine("Missing or invalid user_pool_id.");
    return;
}

if ((app.JsonTypeOf("client_id") != 1) || (app.StringOf("client_id") == "")) {
    Debug.WriteLine("Missing or invalid client_id.");
    return;
}

if ((app.JsonTypeOf("account_key") != 1) || (app.StringOf("account_key") == "")) {
    Debug.WriteLine("Missing or invalid account_key.");
    return;
}

string clientId = app.StringOf("client_id");
Chilkat.StringBuilder endpoint = new Chilkat.StringBuilder();
endpoint.Append("https://cognito-idp.");
endpoint.Append(app.StringOf("region"));
endpoint.Append(".amazonaws.com/");
Chilkat.Http http = new Chilkat.Http();
http.RequireSslCertVerify = true;
http.FollowRedirects = false;
http.ConnectTimeout = 20;
http.ReadTimeout = 60;
Chilkat.HttpResponse resp = new Chilkat.HttpResponse();
Chilkat.JsonObject body = new Chilkat.JsonObject();
Chilkat.JsonObject result = new Chilkat.JsonObject();
result.Strict = true;
Chilkat.JsonObject cached = new Chilkat.JsonObject();
cached.Strict = true;
success = cached.LoadFile("qa_data/tokens/cognito-user.json");
if (success != true) {
    Debug.WriteLine("Could not load qa_data/tokens/cognito-user.json.");
    return;
}

if ((cached.JsonTypeOf("client_id") != 1) || (cached.StringOf("client_id") == "")) {
    Debug.WriteLine("Missing or invalid client_id.");
    return;
}

if (cached.StringOf("client_id") != app.StringOf("client_id")) {
    Debug.WriteLine("Saved data belongs to another client, pool, or local account.");
    return;
}

if ((cached.JsonTypeOf("user_pool_id") != 1) || (cached.StringOf("user_pool_id") == "")) {
    Debug.WriteLine("Missing or invalid user_pool_id.");
    return;
}

if (cached.StringOf("user_pool_id") != app.StringOf("user_pool_id")) {
    Debug.WriteLine("Saved data belongs to another client, pool, or local account.");
    return;
}

if ((cached.JsonTypeOf("account_key") != 1) || (cached.StringOf("account_key") == "")) {
    Debug.WriteLine("Missing or invalid account_key.");
    return;
}

if (cached.StringOf("account_key") != app.StringOf("account_key")) {
    Debug.WriteLine("Saved data belongs to another client, pool, or local account.");
    return;
}

//  Choose the expected token type independently of the incoming JWT.
string expectedUse = "access";
string requiredScope = "aws.cognito.signin.user.admin";
if ((expectedUse != "access") && (expectedUse != "id")) {
    Debug.WriteLine("Choose access or id.");
    return;
}

string 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 == "")) {
    Debug.WriteLine("Missing JWT.");
    return;
}

Chilkat.Jwt jwt = new Chilkat.Jwt();
Chilkat.JsonObject header = new Chilkat.JsonObject();
header.Strict = true;
success = header.Load(jwt.GetHeader(encodedToken));
if (success != true) {
    Debug.WriteLine("Invalid JWT header.");
    return;
}

if (header.StringOf("alg") != "RS256") {
    Debug.WriteLine("Expected RS256; do not trust the token algorithm without an allowlist.");
    return;
}

if ((header.JsonTypeOf("kid") != 1) || (header.StringOf("kid") == "")) {
    Debug.WriteLine("Missing or invalid kid.");
    return;
}

Chilkat.StringBuilder issuer = new Chilkat.StringBuilder();
issuer.Append(endpoint.GetAsString());
issuer.Append(app.StringOf("user_pool_id"));
Chilkat.StringBuilder jwksUrl = new 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 != 200) {
    Debug.WriteLine("HTTP status: " + Convert.ToString(resp.StatusCode));
    success = result.Load(resp.BodyStr);
    if (success == true) {
        Debug.WriteLine("Error type: " + result.StringOf("__type"));
        Debug.WriteLine("OAuth error: " + result.StringOf("error"));
    }

    //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
    return;
}

if (success != true) {
    Debug.WriteLine("The HTTP exchange did not complete.");
    return;
}

success = result.Load(resp.BodyStr);
if (success != true) {
    Debug.WriteLine("Expected a JSON response.");
    return;
}

if (result.JsonTypeOf("keys") != 4) {
    Debug.WriteLine("Expected a JWKS keys array.");
    return;
}

int i = 0;
int count = result.SizeOfArray("keys");
int matches = 0;
Chilkat.JsonObject jwk = new Chilkat.JsonObject();
while (i < count) {
    result.I = i;
    if (result.StringOf("keys[i].kid") == header.StringOf("kid")) {
        matches = matches + 1;
        success = result.ObjectOf2("keys[i]",jwk);
        if (success != true) {
            Debug.WriteLine("Could not read the matching key.");
            return;
        }

    }

    i = i + 1;
}

if (matches != 1) {
    Debug.WriteLine("Expected exactly one matching signing key.");
    return;
}

if ((jwk.StringOf("kty") != "RSA") || (jwk.StringOf("use") != "sig") || (jwk.StringOf("alg") != "RS256")) {
    Debug.WriteLine("Unexpected signing-key type, use, or algorithm.");
    return;
}

Chilkat.PublicKey publicKey = new Chilkat.PublicKey();
success = publicKey.LoadFromString(jwk.Emit());
if (success != true) {
    Debug.WriteLine("Could not load the RSA JWK.");
    return;
}

success = jwt.VerifyJwtPk(encodedToken,publicKey);
if (success != true) {
    Debug.WriteLine("Invalid JWT signature.");
    return;
}

//  Only now inspect trusted claims. A valid signature alone is not sufficient.
Chilkat.JsonObject claims = new Chilkat.JsonObject();
claims.Strict = true;
success = claims.Load(jwt.GetPayload(encodedToken));
if (success != true) {
    Debug.WriteLine("Invalid JWT claims.");
    return;
}

if (claims.StringOf("iss") != issuer.GetAsString()) {
    Debug.WriteLine("JWT issuer mismatch.");
    return;
}

if (claims.StringOf("token_use") != expectedUse) {
    Debug.WriteLine("Wrong token purpose.");
    return;
}

if ((claims.JsonTypeOf("exp") != 2) || (claims.JsonTypeOf("iat") != 2)) {
    Debug.WriteLine("Missing numeric expiration or issue time.");
    return;
}

if (jwt.IsTimeValid(encodedToken,60) != true) {
    Debug.WriteLine("JWT is expired or not yet valid.");
    return;
}

if (expectedUse == "id") {
    if (claims.StringOf("aud") != clientId) {
        Debug.WriteLine("ID token audience mismatch.");
        return;
    }

}
else {
    if (claims.StringOf("client_id") != clientId) {
        Debug.WriteLine("Access token client mismatch.");
        return;
    }

    //  Whole-word scope matching, not a substring match.
    Chilkat.StringBuilder scopes = new Chilkat.StringBuilder();
    scopes.Append(" ");
    scopes.Append(claims.StringOf("scope"));
    scopes.Append(" ");
    Chilkat.StringBuilder wantedScope = new Chilkat.StringBuilder();
    wantedScope.Append(" ");
    wantedScope.Append(requiredScope);
    wantedScope.Append(" ");
    if ((requiredScope != "") && (scopes.Contains(wantedScope.GetAsString(),true) != true)) {
        Debug.WriteLine("Required scope is absent.");
        return;
    }

}

if ((claims.JsonTypeOf("sub") != 1) || (claims.StringOf("sub") == "")) {
    Debug.WriteLine("Missing or invalid sub.");
    return;
}

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