# Add Cognito Authentication to an API Gateway in AWS CDK

Yes. An agent adds a Cognito user pool and authorizer to your CDK REST API, keeps CORS preflight open, writes assertion tests, synthesizes and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/add-cognito-auth/aws-cdk/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent clones the repository into its own cloud sandbox and reads the stack before it adds a construct. In an example like `typescript/api-cors-lambda-crud-dynamodb` in aws-samples/aws-cdk-examples, `package.json` pins `aws-cdk-lib` 2.262.1 and `aws-cdk` 2.1133.0, builds with `tsc`, runs tests with `jest` through `@swc/jest`, and installs the Lambda dependencies in a `postinstall` step; `cdk.json` runs `npx tsc && npx tsx index.ts` and sets the usual feature flags, including `@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId`. `index.ts` holds everything: a DynamoDB `Table` named `items` with an `itemId` partition key and `RemovalPolicy.DESTROY`, five `NodejsFunction`s on `Runtime.NODEJS_24_X` for `get-one`, `get-all`, `create`, `update-one` and `delete-one` with the table name and key in their environment, a `RestApi` called `itemsApi`, and the routes `GET` and `POST` on `/items` and `GET`, `PATCH` and `DELETE` on `/items/{id}`. An `addCorsOptions` helper adds an `OPTIONS` method with a `MockIntegration` to each resource, and its allowed headers already include `Authorization`. The file ends by creating the `App`, the stack and calling `app.synth()` at module scope, and `jest.config.js` matches `**/*.test.ts` but no test file exists.

The agent adds the identity side first: a `UserPool` from `aws-cdk-lib/aws-cognito` with `signInAliases: { email: true }`, self sign-up off, a password policy, and `RemovalPolicy.DESTROY` to match the table's stance in this example, and a `UserPoolClient` with `generateSecret: false` and the SRP and user-password auth flows, so a web or mobile client can sign in without a secret. Then a `CognitoUserPoolsAuthorizer` from `aws-cdk-lib/aws-apigateway` with `cognitoUserPools: [userPool]`, attached through the `RestApi`'s `defaultMethodOptions` as `{ authorizer, authorizationType: AuthorizationType.COGNITO }`, so all five existing `addMethod` calls require a token without being edited. `addCorsOptions` gets one change: its `OPTIONS` method passes `authorizationType: AuthorizationType.NONE`, because a browser's preflight carries no token and a protected `OPTIONS` route breaks every cross-origin call. `CfnOutput`s for the pool id and client id join the API URL the `RestApi` already outputs.

To make the stack testable, the agent moves the `App` creation and `app.synth()` into a new `app.ts` and points `cdk.json`'s `app` at it, leaving `index.ts` to export the stack class; without that, importing the stack in a test would synthesize on import. It then writes `index.test.ts` with `Template.fromStack` from `aws-cdk-lib/assertions`: one `AWS::Cognito::UserPool`, one `AWS::ApiGateway::Authorizer` with `Type: COGNITO_USER_POOLS`, every `AWS::ApiGateway::Method` whose `HttpMethod` is not `OPTIONS` has `AuthorizationType: COGNITO_USER_POOLS` and references the authorizer, and every `OPTIONS` method has `NONE`. The Lambda handlers are left as they are; the pull request notes that `event.requestContext.authorizer.claims.sub` is now available to `create.ts` if items should be owned per user, which is a separate change.

The agent runs `npm install`, `npm run build`, `npx jest` and `npx cdk synth` in the sandbox, none of which need AWS credentials for this stack, and reads the synthesized template to confirm the authorizer and method settings match the test. The outputs go in the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add Cognito authentication to the REST API in this CDK app. Read cdk.json, package.json and the stack file first. Add a Cognito user pool with email sign-in and a user pool client without a secret, a CognitoUserPoolsAuthorizer, and set the RestApi's default method options so every existing method requires a Cognito token, while the OPTIONS methods used for CORS preflight stay unauthenticated. Add outputs for the pool id and client id. If the stack file creates the App and calls synth at module scope, move that into a separate entry file and update cdk.json so the stack class can be imported by tests. Write assertion tests with Template.fromStack that check the user pool, the authorizer type, that every non-OPTIONS method is COGNITO_USER_POOLS and every OPTIONS method is NONE. Run the build, the tests and cdk synth, and open a pull request that explains how a client obtains a token. Do not change the Lambda handlers.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request on its own branch that edits `index.ts` (the user pool, client, authorizer, default method options, the `OPTIONS` exception and the outputs) and `cdk.json`, and adds `app.ts` and `index.test.ts`. The description shows the relevant part of the synthesized template, the `jest` output, and a short section on signing in against the user pool with the client id to obtain an id token for the `Authorization` header.

The run's record keeps `npm run build`, `npx jest` and `npx cdk synth` with their output, so a reviewer can see the template the tests ran against without synthesizing locally.

Before merging, a reviewer decides whether self sign-up and the password policy match the product, whether the pool should keep `RemovalPolicy.DESTROY` outside this example, and whether the handlers should start scoping items by the caller's `sub`.

## Run it on every new API stack

In the console, an automation in the Project that has the repository, with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and `branch_patterns` for your default branch, starts one run per pull request, with the pull request as its context; its prompt asks the run to add the same authorizer and tests on the pull request's branch when it adds a `RestApi`, or to comment with the patch.

From your own server, the same work is one `POST /o/{org}/sessions` per stack repository with this body and the repository in `resources`, and a webhook on the API key reports `run.completed` with the `session_url` to read the pull request link.

## Why run it on Rush?

Protecting an API with Cognito is a handful of constructs plus two traps: a preflight route that inherits the authorizer and breaks every browser client, and a stack file that synthesizes on import and cannot be tested. The agent reads the CORS helper and the module-scope `synth` before writing, handles both, and proves the method settings with assertion tests against the synthesized template.

The build, tests and `cdk synth` run in the sandbox with the repository's own pinned `aws-cdk-lib`, and the output stays in the record. Several stacks can get the same change at the same time in separate sandboxes.

## Frequently asked questions

### Will CORS still work from a browser?

Yes. The `OPTIONS` methods the CORS helper adds are set to `AuthorizationType.NONE`, and the test asserts it for every resource. The allowed headers already include `Authorization`, so the real request can carry the token.

### Does it need AWS credentials?

No. `cdk synth`, `tsc` and the assertion tests work from the code alone for this stack, and the agent does not run `cdk deploy`. Deploying the new pool and authorizer is the reviewer's step.

### Why move the App into a separate file?

Because `index.ts` creates the `App` and calls `app.synth()` at module scope, so importing the stack class in a test would synthesize the whole app on import. `app.ts` becomes the entry point in `cdk.json` and `index.ts` exports the stack for tests.

### Can it use an existing user pool instead?

Yes. Give the pool id or ARN in `input` and the agent uses `UserPool.fromUserPoolId` or `fromUserPoolArn` for the authorizer and creates no pool, with the test adjusted to assert on the authorizer only.

### What about per-user data in the handlers?

Out of scope for this run by the prompt's own rule. The pull request points out that the caller's `sub` claim is now in the event, and a follow-up on the same session can add an owner attribute to `create.ts` and filter `get-all.ts` by it.

## More AWS CDK jobs

- [Add a Dead Letter Queue to a Lambda in AWS CDK from a Linear Issue](https://getrush.ai/run/add-dlq/aws-cdk/)
- [Enable DynamoDB Point-in-Time Recovery in an AWS CDK Stack from a Linear Issue](https://getrush.ai/run/add-dynamodb-point-in-time-recovery/aws-cdk/)
- [Set Up GitHub Actions CI for an AWS CDK App](https://getrush.ai/run/add-github-actions-ci/aws-cdk/)

## More jobs like this: Hand off a long task

- [Declare the Collections an Ansible Role Depends On](https://getrush.ai/run/add-collection-requirements/ansible/)
- [Add Command Palette Commands to a Textual App](https://getrush.ai/run/add-command-palette/textual/)
- [Generate compile_commands.json for a Bazel C++ Project](https://getrush.ai/run/add-compile-commands/bazel/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
