# Authenticate requests to Cube with AWS Cognito

## Introduction

In this guide, you'll learn how to integrate AWS Cognito authentication with a
Cube deployment. If you already have a pre-existing Cognito User Pool in AWS
that you'd like to re-use, please skip ahead to
[Configure Cube](#configure-cube).

## Create and configure a User Pool

If you haven't already created a User Pool, please follow [the instructions in
the AWS Cognito documentation][link-aws-cognito-hosted-ui] to create one, along
with enabling the Hosted UI.

### Custom claims

To add custom claims to the JWT, you will need to associate [a Lambda
function][link-aws-lambda] to the [Pre Token Generation event
trigger][link-aws-cognito-pre-token] available on your User Pool.

First, go to the AWS Lambda Console and create new a Lambda function:

<div style={{ textAlign: "center" }}>
  <img
    src="https://ucarecdn.com/2545ca40-ff29-476b-8068-3f7119c13e08/"
    style={{ border: "none" }}
    width="80%"
  />
</div>

Add the following code to the Lambda function:

```javascript
exports.handler = (event, context, callback) => {
  event.response = {
    claimsOverrideDetails: {
      claimsToAddOrOverride: {
        "http://localhost:4000/": JSON.stringify({
          company_id: "company1",
          user_id: event.request.userAttributes.sub,
          roles: ["user"]
        })
      }
    }
  }
  
  callback(null, event)
}
```

Then navigate to the Amazon Cognito User Pools Console, select Triggers from the
left sidebar and associate the Lambda function you created previously:

<div style={{ textAlign: "center" }}>
  <img
    src="https://ucarecdn.com/42dc3c26-9574-4d69-a029-2914bacf7c9b/"
    style={{ border: "none" }}
    width="80%"
  />
</div>

You can find more examples of [modifying claims in JWTs
here][link-aws-cognito-pretoken-example].

## Configure Cube

Now we're ready to configure Cube to use AWS Cognito. Go to your Cube project
and open the `.env` file and add the following, replacing the values wrapped in
`<>`.

```dotenv
CUBEJS_JWK_URL=https://cognito-idp.<AWS_REGION>.amazonaws.com/<USER_POOL_ID>/.well-known/jwks.json
CUBEJS_JWT_AUDIENCE=<APPLICATION_URL>
CUBEJS_JWT_ISSUER=https://cognito-idp.<AWS_REGION>.amazonaws.com/<USER_POOL_ID>
CUBEJS_JWT_ALGS=RS256
CUBEJS_JWT_CLAIMS_NAMESPACE=<CLAIMS_NAMESPACE>
```

## Testing with the Developer Playground

### Retrieving a JWT

Go to the [OpenID Playground from Auth0][link-openid-playground] to and click
Configuration.

<div style={{ textAlign: "center" }}>
  <img
    src="https://ucarecdn.com/a40aaeba-1a16-426c-b8a0-8e2be23572e2/"
    style={{ border: "none" }}
    width="80%"
  />
</div>

Change the Server Template to Custom, and enter the following values:

<div style={{ textAlign: "center" }}>
  <img
    src="https://ucarecdn.com/bdbbc8ab-0274-479c-aae3-98507722d0b7/"
    style={{ border: "none" }}
    width="80%"
  />
</div>

- **Discovery Document URL**:
  `https://cognito-idp.<AWS_REGION>.amazonaws.com/<USER_POOL_ID>/.well-known/openid-configuration`
- **OIDC Client ID**: Retrieve from App Client settings page in AWS Cognito User
  Pool Console
- **OIDC Client Secret**: Retrieve from App Client settings page in AWS Cognito
  User Pool Console

Click 'Use Discovery Document' to auto-fill the remaining values, then click
Save.

<WarningBox>

If you haven't already, go back to the AWS Cognito App Client's settings and add
`https://openidconnect.net/callback` to the list of allowed callback URLs.

</WarningBox>

Now click Start; and in a separate tab, go to the App Client's settings page and
click the Launch Hosted UI button.

<div style={{ textAlign: "center" }}>
  <img
    src="https://ucarecdn.com/fdeda9b5-d00e-4236-baf7-1a026bce942a/"
    style={{ border: "none" }}
    width="80%"
  />
</div>

If the login is successful, you should be redirected to the OpenID Connect
Playground. Click on the Exchange button to exchange the code for your tokens:

<div style={{ textAlign: "center" }}>
  <img
    src="https://ucarecdn.com/38c9c14f-6825-4dc6-8d24-847fb3f17c95/"
    style={{ border: "none" }}
    width="80%"
  />
</div>

Click Next, and continue on to the next section and click the Verify button to
verify the JWT signature as well as decode the identity token:

<div style={{ textAlign: "center" }}>
  <img
    src="https://ucarecdn.com/a7dd0870-f4ce-410a-88a4-40a5c42ee835/"
    style={{ border: "none" }}
    width="80%"
  />
</div>

### Set JWT in Developer Playground

Now open the Developer Playground (at `http://localhost:4000`) and on the Build
page, click Add Security Context.

<div style={{ textAlign: "center" }}>
  <img
    src="https://ucarecdn.com/f63817d8-9729-4b7f-a36c-02518de422e9/"
    style={{ border: "none" }}
    width="80%"
  />
</div>

Click the Token tab, paste the `id_token` from OpenID Playground and click the
Save button.

<div style={{ textAlign: "center" }}>
  <img
    src="https://ucarecdn.com/892b39e7-4d57-4dba-957a-dad8ec34fe68/"
    style={{ border: "none" }}
    width="80%"
  />
</div>

Close the popup and use the Developer Playground to make a request. Any data
models using the [Security Context][ref-sec-ctx] should now work as expected.

[link-aws-cognito-hosted-ui]:
  https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-app-integration.html#cognito-user-pools-create-an-app-integration
[link-aws-cognito-pre-token]:
  https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html
[link-aws-cognito-pretoken-example]:
  https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html#aws-lambda-triggers-pre-token-generation-example-1
[link-aws-lambda]: https://docs.aws.amazon.com/lambda/latest/dg/welcome.html
[link-openid-playground]: https://openidconnect.net/
[ref-sec-ctx]: /product/auth/context

