Protect a DaloyJS API with AWS Cognito
Amazon Cognito user pools provide hosted sign-up, sign-in, MFA, and federation. This guide verifies the access tokens Cognito issues using the AWS-recommended aws-jwt-verify library, pure TypeScript, zero runtime dependencies, and edge-runtime compatible via Web Crypto.
- 01asyncClient appCognito (user pool)Sign in via hosted UI / authorization-code flowCognito issues access + ID tokens (RS256)
- 02requestClient appDaloyJS APICall API with Authorization: Bearer <access token>
- 03asyncDaloyJS APICognito JWKSCognitoJwtVerifier fetches signing keys (cached)hydrate() pre-warms the JWKS cache
- 04noteDaloyJS APIDaloyJS APIVerify signature, tokenUse, clientId, scope & cognito:groups
- 05responseDaloyJS APIClient appReturn protected data after requireAuth passes
1. Provision
- Create a user pool in the AWS console, then add an app client. Note the User pool ID (e.g.
us-east-1_AbCdEfGhI) and the App client ID. - Configure a resource server with custom scopes (e.g.
my-api/read,my-api/write) and authorize them on the app client. - Enable a hosted UI domain or use the OAuth 2.0 authorization-code flow from your client app. Your DaloyJS API only needs to verify the resulting access token, it never sees passwords.
2. Install
3. Environment variables
4. Plugin
verifier.hydrate() downloads the JWKS up front so the first authenticated request doesn't pay a network round-trip. Subsequent key rotations are picked up automatically.
5. Guard a route
Trusting multiple pools or IdPs
CognitoJwtVerifier.create([...]) accepts an array of pool configurations to trust JWTs from more than one user pool. To trust a Cognito pool and a non-Cognito OIDC IdP, use the generic JwtVerifier with validateCognitoJwtFields in a customJwtCheck.
Notes on tokens
- Access tokens carry
scope(space-separated string) andcognito:groups: use them for API authorization. - ID tokens carry user attributes (
email,name) and anaudclaim. Verify them withtokenUse: "id"when your UI needs profile data. - Cognito signs with RS256. The library refuses
alg: noneand symmetric algorithms by design.
See also Entra ID, Auth0, and the auth integrations overview.