Skip to content

Serverless Auth with Cognito User Pools

Cognito User Pools as a managed identity backend: sign-up, confirm and sign-in without your own auth server, the three tokens properly understood, and an API Gateway endpoint secured by a Cognito authorizer.

≈ 12 min readSoftwareAWSCloud

Cognito takes password handling off your hands – it doesn’t take the decision about who owns your users’ identities off your hands. These two things get lumped together all the time. The signUp() call is integrated in an afternoon; the sub that Cognito assigns along the way then travels as a foreign key through every table and stays for years. The integration is cheap, owning the identities is expensive.

Storing passwords, sending confirmation emails, signing and rotating tokens – solved problems, and rarely what sets a product apart from the competition. A homegrown auth server isn’t differentiation but a surface that has to be maintained and secured for good. AWS has a managed building block for this responsibility: Cognito User Pools. What’s interesting about it is less the API call than the trade-off behind it: Which operational responsibility do I hand over, and what price do I pay if I switch later? That is exactly what I take apart here – with one continuous example that shows the path from registration to the secured endpoint.

To me, serverless mainly means handing over operational responsibility where it creates no competitive advantage. Your own auth server rarely is one – it is an attack surface you have to maintain.

What a user pool actually is#

A Cognito User Pool is a managed directory for your end users plus all the machinery around it: registration, email or SMS verification, sign-in, password reset and issuing tokens. Your application no longer stores passwords – it only talks to Cognito. That is the decisive change of perspective: it isn’t your app that decides whether a password is correct, it’s the user pool. In the end, your app just gets a signed token and has to be able to trust that token.

You need to keep two objects apart. The user pool itself is the directory including its policies – password rules, which attributes are required, which get verified automatically. The app client is the application that authenticates against the pool; it defines which auth flows are allowed and how long a refresh token stays valid. A pool can have several app clients – for example one for the web and one for the native app.

This is what it looks like minimally in CDK. I deliberately stick with the L1 constructs (Cfn...) because they map one to one to the CloudFormation resources, so you see exactly what gets created:

const {
  CfnUserPool,
  CfnUserPoolClient,
  CfnUserPoolGroup,
} = require('@aws-cdk/aws-cognito');

const userPool = new CfnUserPool(this, 'UserPool', {
  userPoolName: 'UserPool',
  adminCreateUserConfig: {
    allowAdminCreateUserOnly: false,
  },
  policies: {
    passwordPolicy: {
      minimumLength: 6,
    },
  },
  schema: [
    {
      attributeDataType: 'String',
      name: 'email',
      required: true,
    },
  ],
  autoVerifiedAttributes: ['email'],
});

const userPoolClient = new CfnUserPoolClient(this, 'UserPoolClient', {
  clientName: 'UserPoolClient',
  explicitAuthFlows: ['ALLOW_USER_SRP_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],
  refreshTokenValidity: 30,
  userPoolId: userPool.ref,
});

autoVerifiedAttributes: ['email'] makes Cognito automatically send a confirmation code by email after registration. refreshTokenValidity: 30 sets the lifetime of the refresh token to 30 days – more on that in a moment. If you prefer building with the higher-level L2 constructs (UserPool, UserPoolClient), you get more convenient defaults; for getting started, I find the explicit L1 variant more instructive. If you are wondering why I describe infrastructure in a programming language at all instead of YAML: I explained that in CDK: Infrastructure in a Programming Language.

Sign-up, confirm, sign-in#

A user’s lifecycle has three stations. On the client – or, as in my example, in a thin Node backend – I use amazon-cognito-identity-js, the official JavaScript SDK for user pools. Registration, confirmation, sign-in:

import {
  CognitoUserPool,
  CognitoUser,
  AuthenticationDetails,
  CognitoUserAttribute,
} from 'amazon-cognito-identity-js';

const userPool = new CognitoUserPool({
  UserPoolId: process.env.USER_POOL_ID,
  ClientId: process.env.USER_POOL_CLIENT_ID,
});

// 1) sign-up: create the user, Cognito emails a confirmation code
userPool.signUp(
  username,
  password,
  [new CognitoUserAttribute({ Name: 'email', Value: username })],
  [],
  (err, result) => {
    /* result.user is created but not yet confirmed */
  }
);

// 2) confirm: user submits the code from the email
const cognitoUser = new CognitoUser({ Username: username, Pool: userPool });
cognitoUser.confirmRegistration(code, true, (err, result) => {
  /* result === 'SUCCESS' */
});

// 3) sign-in: authenticate and receive tokens
cognitoUser.authenticateUser(
  new AuthenticationDetails({ Username: username, Password: password }),
  {
    onSuccess(session) {
      const idToken = session.getIdToken().getJwtToken();
      const accessToken = session.getAccessToken().getJwtToken();
      // refresh token is available too, but opaque
    },
    onFailure(err) {
      /* wrong password, unconfirmed user, ... */
    },
  }
);

The important point: the confirm step sits between steps one and three. A freshly registered user is UNCONFIRMED at first and can’t sign in until they confirm the code delivered by email. Cognito sends that email itself.

The three tokens – and why “three JWTs” is wrong#

After a successful sign-in, Cognito returns exactly three tokens. That sounds trivial, but a stubborn misconception lives here: people often say you get “three JWTs”. That isn’t true. Two of them are JWTs, one explicitly is not.

The ID token is a JWT and carries the user’s identity – claims such as sub, email and cognito:username. It answers the question “who is this user?” and is the standard token for the classic API Gateway Cognito authorizer. The access token is also a JWT, but it carries OAuth scopes and answers “what is this client allowed to do?”; it comes into play as soon as you use scope-based authorization with resource servers. Finally, the refresh token is not a JWT but an encrypted string that only Cognito can read. It is long-lived – 30 days in my configuration – and serves only to exchange it for fresh ID and access tokens without entering the password again.

Why is this more than hair-splitting? Because you can verify a JWT locally – check the signature, check the expiry, done – but not an opaque token. And if the frontend sends the wrong token to the API, you get a 401 without understanding why. For the REST Cognito authorizer without configured scopes, the ID token goes into the header. Only when you configure authorizationScopes does the gateway expect the access token. This exact mix-up is one of the most common sources of errors.

A decoded ID token essentially looks like this – you can see the issuer, the audience and the intended use:

{
  "sub": "a1b2c3d4-....",
  "email": "user@example.com",
  "cognito:username": "user@example.com",
  "aud": "the-app-client-id",
  "iss": "https://cognito-idp.eu-central-1.amazonaws.com/eu-central-1_ABC123",
  "token_use": "id",
  "exp": 1611060000
}

Securing the endpoint – without your own verification code#

Now comes the part where managed auth really pays off. I could check the token myself in every Lambda: load the pool’s JWKS document, find the matching key via the kid from the token header, convert it to a PEM and verify the signature. I built exactly that in a classic Express backend, and it is instructive to have seen it done by hand once:

export async function validateToken({ token, region, userPoolId }) {
  const response = await fetch(
    `https://cognito-idp.${region}.amazonaws.com/${userPoolId}/.well-known/jwks.json`
  );
  const { keys } = await response.json();

  const decoded = jwt.decode(token, { complete: true });
  if (!decoded) throw new Error('Invalid JWT');

  const key = keys.find((k) => k.kid === decoded.header.kid);
  if (!key) throw new Error('Invalid JWT');

  const pem = jwkToPem({ kty: key.kty, n: key.n, e: key.e });
  return new Promise((resolve, reject) => {
    jwt.verify(token, pem, (err, payload) =>
      err ? reject(new Error('Invalid JWT')) : resolve(payload)
    );
  });
}

That works – but it is code I have to write, test and maintain, and it shows up again in every secured route. The API Gateway Cognito authorizer takes exactly this work off your hands. You point the gateway at the user pool, and it handles the entire check as a managed service: signature against the pool JWKS, exp, aud, iss. If a valid token arrives, the Lambda gets invoked; if an invalid or expired one arrives, the gateway answers with 401 before your function even starts. No verification code of your own.

In CDK, you connect this to a REST API route via a CognitoUserPoolsAuthorizer:

import {
  RestApi,
  CognitoUserPoolsAuthorizer,
  AuthorizationType,
  LambdaIntegration,
} from '@aws-cdk/aws-apigateway';

const authorizer = new CognitoUserPoolsAuthorizer(this, 'Authorizer', {
  cognitoUserPools: [userPool],
});

const api = new RestApi(this, 'Api');
const items = api.root.addResource('items');

items.addMethod('GET', new LambdaIntegration(getItemsFn), {
  authorizer,
  authorizationType: AuthorizationType.COGNITO,
});

If you work directly at the API Gateway level – in an OpenAPI definition, for example – you’ll recognize the same configuration in its raw form. The authorizer is of type cognito_user_pools, references the pool by ARN and reads the token from the Authorization header:

{
  "type": "apiKey",
  "name": "Authorization",
  "in": "header",
  "x-amazon-apigateway-authtype": "cognito_user_pools",
  "x-amazon-apigateway-authorizer": {
    "type": "cognito_user_pools",
    "providerARNs": [
      "arn:aws:cognito-idp:eu-central-1:123456789012:userpool/eu-central-1_ABC123"
    ],
    "identitySource": "method.request.header.Authorization"
  }
}

So the client simply sends its ID token in the Authorization header – in practice usually as Bearer <idToken> – and doesn’t have to take care of anything else. The whole flow looks like this:

sequenceDiagram
  participant C as Client
  participant Cog as Cognito User Pool
  participant GW as API Gateway
  participant L as Lambda
  C->>Cog: sign-in (username / password)
  Cog-->>C: ID + Access + Refresh tokens
  C->>GW: GET /items<br/>Authorization: Bearer idToken
  GW->>Cog: verify JWT via JWKS (signature, exp, aud, iss)
  GW->>L: invoke (token valid)
  L-->>C: 200 OK

Lambda triggers: hooking your own logic into the flow#

Sometimes the standard flow isn’t enough. For example, you want to allow only email addresses from a specific company domain, or write additional data to a table of your own during registration. For this, the user pool offers Lambda triggers – entry points at defined places in the lifecycle. Available in 2021 are, among others, PreSignUp, PostConfirmation, PreAuthentication, PostAuthentication, PreTokenGeneration and CustomMessage.

A PreSignUp trigger runs before Cognito creates a new user. This is where I check the email domain, for example:

exports.handler = async (event) => {
  const email = event.request.userAttributes.email || '';
  if (!email.endsWith('@example.com')) {
    throw new Error('Only example.com addresses are allowed');
  }
  // do NOT auto-confirm: keep the email verification step intact
  event.response.autoConfirmUser = false;
  return event;
};

Two things are crucial here, and both are classic pitfalls. First: the trigger must return the event object at the end, unchanged except for the intended response fields. If you forget the return event, the flow aborts. Second: autoConfirmUser and the related auto-verify fields are powerful. If you accidentally set them to true, a user bypasses the email confirmation step completely – and later you wonder about unconfirmed addresses in the pool.

The small component picture for this:

flowchart LR
  Pool[User Pool + App Client] -->|JWKS| GW[API Gateway<br/>Cognito Authorizer]
  GW --> Fn[Lambda]
  Trigger[PreSignUp trigger] -.-> Pool

The real trade-off: managed identity versus vendor lock-in#

Everything shown so far is the credit side: no password handling, no homegrown token issuing, no verification logic in every route. This responsibility, including the attack surface, moves to AWS – usually the heavier item. Still, I won’t hide the debit side: lock-in to the vendor.

This lock-in is more concrete than it seems at first. Your tokens are signed against this pool’s JWKS, your client talks through the Cognito SDK, your triggers are tailored to Cognito’s event structure – and weighing heaviest: every user’s sub is a UUID assigned by Cognito that travels as a foreign key across your databases. It isn’t the login code that sticks, it’s these identities.

Two edge cases make this tangible. Cognito doesn’t hand out password hashes: if you move away, you can’t quietly take your users with you – either everyone resets their password, or you migrate them lazily on their next login through a UserMigration trigger on the target system. And everything beyond the standard – custom attributes, SRP assumptions in the client, MFA configuration – is Cognito vocabulary that another provider doesn’t speak one to one. So the migration risk doesn’t sit in the auth flow, which you can rebuild in days, but in the identities and their references, which have grown over years.

This turns into a clear decision grid. For standard sign-in with email and password, small to medium teams without dedicated security staff and without a multi-cloud requirement, managed identity almost always wins – the operations you save clearly outweigh the lock-in risk. I would reconsider as soon as an existing identity provider is in place in-house, real vendor portability is required, or data residency dictates where identities may live at all. The trade-off doesn’t go away – but you make it deliberately instead of by reflex, and you make it at the start, when it is still cheap.

An important distinction: infrastructure auth is not resolver auth#

Finally, the distinction that blurs fastest in practice. What the Cognito authorizer does at the API Gateway is infrastructure or edge auth. It answers a single, coarse question: “Is the caller authenticated at all?” If the token is valid, the request gets through – if it isn’t, it gets thrown out with 401 before any of your own code runs. That is a bouncer, not a case worker.

What the authorizer doesn’t do: decide whether this specific user may see or change this specific object. May user A delete user B’s comment? May someone only query their own orders? That is fine-grained authorization, and it belongs in your application logic – in a GraphQL API, for example, in the resolver context, where you check the identity from the token against the actual data objects. The authorizer gives you the reliable identity; which permissions you enforce with it remains your job. Keeping these two levels cleanly apart saves a lot of confusion – and prevents the fallacy that with an authorizer, “authorization is done”.

For the setup shown here – user pool, standard login and a secured API endpoint – Cognito takes a lot of infrastructure off your hands. You can build a first end-to-end path with it at a manageable effort; it only becomes production-ready with settled recovery flows, MFA, monitoring and fine-grained authorization. The authorizer provides the reliable identity; the permissions on concrete domain objects deliberately stay in your application logic. You pay the price, the vendor lock-in, with your eyes open – and you make the decision where it belongs: at the architecture level, not in passing with the first API call.

Further reading#

Revised and translated from German with the help of AI.