---
title: "Integrate the Token Handler with an API Gateway"
description: "Deploy the OAuth Agent and OAuth Proxy using API Gateway public URLs that the SPA calls."
url: "https://curity.io/resources/learn/token-handler-integrate-gateway/"
date: "2024-12-01"
area: "tutorials"
topic: "getting-started"
pagegroup: "tokenhandler-getting-started"
---

# Integrate the Token Handler with an API Gateway

After completing the [First Configuration](https://curity.io/resources/learn/token-handler-first-configuration/), the final deployment task is to provide token handler URLs that the SPA can call. These URLs must be in the same parent site as the SPA's web origin. An API gateway provides the token handler public URLs and SSL certificates. Once URLs are available the SPA can integrate with the token handler to enable the following end-to-end flow, where the SPA sends cookies to API gateway entry points that use the OAuth Proxy to process cookies.

![Token handler components issue first-party cookies on behalf of the Single Page Application](https://curity.io/images/resources/neo_security/token-handler/token-handler.svg) 

Many organizations already have an API gateway and an infrastructure team that can create the token handler host name. Full details of provisioning an API gateway, connecting networking infrastructure and enabling external URLs is a major topic that is not covered here. Instead, the following sections summarize the main steps to integrate the OAuth Proxy and update the API gateway.

## Create the Token Handler Host Name

In deployed environments, use a DNS solution to create the token handler host name. For example, use your cloud platform to create a new DNS A record as a subdomain of the SPA's existing domain. The API gateway can then use API routes that reference the token handler's host name.

## Get the OAuth Proxy

The OAuth Proxy executes as an API gateway plugin for API routes that the SPA calls. Use the [Curity Developer Portal](https://developer.curity.io/releases/token-handler) to download a zip file for a particular API gateway, which contains the proxy files and detailed instructions on how to integrate the plugin with your gateway. Implementations are available for the following popular gateways:

-   Kong
-   OpenResty
-   NGINX
-   AWS API Gateway
-   Azure API Management
-   Google Apigee API Manegement

## Deploy the OAuth Proxy

The main deployment task is integration of the OAuth Proxy plugin with the API gateway. You deploy the plugin files once and can then configure the plugin for multiple API routes. The exact deployment behavior varies depending on the particular gateway and how you administer it. For gateways that can run on a local computer you can see working deployments in the [Token Handler Deployment Example](https://curity.io/resources/learn/token-handler-deployment-example/).

**Kong**

For the Kong API gateway, these are the plugin related tasks:

-   Deploy the OAuth Proxy plugin files and its library dependencies with the gateway.
-   Supply configuration for API routes to define how the OAuth Proxy and CORS plugins process requests.

The following example `docker-compose.yml` file uses a custom Docker image to deploy the plugin and a `kong.yml` file to deploy route configuration. The [detailed tutorial](https://curity.io/resources/learn/kong-oauth-proxy/#deploy-the-oauth-proxy) walks through the deployment steps.

```yaml
services:
  kong:
    image: custom_kong:1.0.0
    ports:
      - 80:3001
    volumes:
      - ./kong.yml:/usr/local/kong/declarative/kong.yml
    environment:
      KONG_DATABASE: 'off'
      KONG_DECLARATIVE_CONFIG: '/usr/local/kong/declarative/kong.yml'
      KONG_PROXY_LISTEN: '0.0.0.0:3000'
      KONG_LOG_LEVEL: 'info'
      KONG_PLUGINS: 'bundled,cors,oauth-proxy'
```

**OpenResty**

For the OpenResty API gateway, these are the plugin related tasks:

-   Deploy the OAuth Proxy plugin files and its library dependencies with the gateway.
-   Supply configuration for API routes to define how the OAuth Proxy and CORS plugins process requests.

The following example `docker-compose.yml` file uses a custom Docker image to deploy the plugin and a `default.conf` file to deploy route configuration. The [detailed tutorial](https://curity.io/resources/learn/openresty-oauth-proxy/#deploy-the-oauth-proxy) walks through the deployment steps.

```yaml
services:
  api-gateway-openresty:
    image: apigateway-openresty:1.0.0
    hostname: apigateway-internal
    ports:
      - 80:3001
    volumes:
      - ./apigateway/openresty/nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf
      - ./apigateway/openresty/default.conf:/etc/nginx/conf.d/default.conf
```

**NGINX**

For the NGINX API gateway, these are the plugin related tasks:

-   Deploy the OAuth Proxy plugin files with the gateway.
-   Supply configuration for API routes to define how the OAuth Proxy and CORS plugins process requests.

The following example `docker-compose.yml` file uses a custom Docker image to deploy the plugin and a `default.conf` file to deploy route configuration. The [detailed tutorial](https://curity.io/resources/learn/nginx-oauth-proxy/#deploy-the-oauth-proxy) walks through the deployment steps.

```yaml
services:
  api-gateway-nginx:
    image: apigateway-nginx:1.0.0
    hostname: apigateway-internal
    ports:
      - 80:3001
    volumes:
      - ./apigateway/nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./apigateway/nginx/default.conf:/etc/nginx/templates/default.conf.template
```

**AWS API Gateway**

For AWS API gateway use the following steps to update the API gateway with plugins. The [detailed tutorial](https://curity.io/resources/learn/aws-oauth-proxy/#deploy-the-oauth-proxy) walks through the deployment steps.

-   Deploy a lambda authorizer that contains the OAuth Proxy module and its route configuraton.
-   Configure CORS for API routes, to grant access to the SPA.

**Azure API Management**

For the Azure API Management gateway use the following steps to update the API gateway with plugins. The [detailed tutorial](https://curity.io/resources/learn/azure-api-management-oauth-proxy/#deploy-the-oauth-proxy) walks through the deployment steps.

-   Deploy an Azure function that contains the OAuth Proxy plugin files and its route configuraton.
-   Configure CORS for API routes, to grant access to the SPA.

**Google Apigee**

For Google Apigee API Management use the following steps to update the API gateway with plugins. The [detailed tutorial](https://curity.io/resources/learn/google-apigee-oauth-proxy/#deploy-the-oauth-proxy) walks through the steps.

-   Upload the OAuth Proxy plugin zip file.
-   Configure policies for CORS and the OAuth Proxy.
-   Apply those policies to API routes.

## Configure the OAuth Proxy

When the SPA calls an API, the browser sends a cookie containing an encrypted access token. Configure the OAuth Proxy so that each of the SPA's API routes decrypts cookies, and forwards access tokens to the API. The exact details of how to configure the OAuth Proxy depend upon the particular API gateway. The following content provides a summary of OAuth Proxy configuration for each supported API gateway, with links to further details.

**Kong**

For the Kong API gateway, use configuration similar to the following so that API routes use both a CORS plugin and the OAuth Proxy plugin. Read more about the [API Route Configuration](https://curity.io/resources/learn/kong-oauth-proxy/#configure-api-routes) details in the main Kong tutorial and see the [Token Handler Deployment Example](https://curity.io/resources/learn/token-handler-deployment-example/) to understand how to automate a Kong deployment.

```yaml
- name: example-api
  url: http://api-internal:3001
  routes:
  - name: example-api-route
    hosts:
    - api.demoapp.example
    paths:
    - /api
  plugins:
  - name: cors
    config:
      origins:
      - https://www.demoapp.example
      credentials: true
      max_age: 86400
  - name: oauth-proxy
    config:
        -----BEGIN ENCRYPTED PRIVATE KEY-----
        MIH0MF8GCSqGSIb3DQEFDTBSMDEGCSqGSIb3DQEFDDAkBBA9BLL4kbxiN4dOlIZE
        nxxsAgIIADAMBggqhkiG9w0CCQUAMB0GCWCGSAFlAwQBKgQQ72a5HguvLkDUto5Q
        gLjuygSBkCOR6pSeXPp1ym5f+oPwYzT99EXbyxELUI43r01IcfY1i8Ib+rPbHB0K
        abRjKb/MnJXaRVS3iaQDYmTLK4SF6YcA3wRJtUZWTeCr79PbzkAootHyRjrYT6jN
        hOm/DLJHiRtNFyRTX+E9r9uMnYACmv6o0lsWScb0NrwPlyW3Ft14ayibtRvCnpEa
        CB3FgLlR9w==
        -----END ENCRYPTED PRIVATE KEY-----
      cookie_key_pass: Password1
```

**OpenResty**

For the OpenResty API gateway, use configuration similar to the following so that API routes use both a CORS plugin and the OAuth Proxy plugin. Read about the [API Route Configuration](https://curity.io/resources/learn/openresty-oauth-proxy/#configure-api-routes) details in the main OpenResty tutorial and see the [Token Handler Deployment Example](https://curity.io/resources/learn/token-handler-deployment-example/) to understand how to automate an OpenResty deployment.

```nginx
server {
    server_name api.demoapp.example;
    listen      3001;

    location /api/ {

        rewrite_by_lua_block {
            
            local cors = require 'cors'
            cors.run({
                origins = {'https://www.demoapp.example'},
                credentials = true,
                max_age = 86400
            })
            
            local oauth_proxy = require 'oauth-proxy'
            oauth_proxy.run({
                cookie_key = '-----BEGIN ENCRYPTED PRIVATE KEY-----\n...',
                cookie_key_pass = 'Password1'
            })
        }

        proxy_pass http://api-internal:3001/;
    }
}
```

**NGINX**

For the NGINX API gateway, use configuration similar to the following so that API routes use both CORS and the OAuth Proxy module. Read about the [API Route Configuration](https://curity.io/resources/learn/nginx-oauth-proxy/#configure-api-routes) details in the main tutorial and see the [Token Handler Deployment Example](https://curity.io/resources/learn/token-handler-deployment-example/) to understand how to automate an NGINX deployment.

```nginx
server {
    server_name api.demoapp.example;
    listen      3000;

    location /api/ {

        set $cors_mode '';
        if ($http_origin = 'https://www.demoapp.example') {
            set $cors_mode 'matched';
        }

        if ($request_method = 'OPTIONS') {
            set $cors_mode '${cors_mode}-preflight';
        }

        if ($cors_mode = 'matched') {
            add_header 'access-control-allow-origin' $http_origin always;
            add_header 'access-control-allow-credentials' true always;
            add_header 'vary' 'origin';
        }

        if ($cors_mode = 'matched-preflight') {
            add_header 'access-control-allow-origin' $http_origin;
            add_header 'access-control-allow-credentials' true;
            add_header 'access-control-allow-methods' 'GET,POST,PUT,PATCH,DELETE';
            add_header 'access-control-allow-headers' $http_access_control_request_headers;
            add_header 'access-control-max-age' 86400;
            add_header 'vary' 'origin, access-control-request-headers';
            return 200;
        }

        oauth_proxy on;
        oauth_proxy_key '-----BEGIN ENCRYPTED PRIVATE KEY-----\n...' 'myS3cret';

        proxy_pass http://api-internal:3001/;
    }
}
```

**AWS API Gateway**

For the AWS API gateway, configure the OAuth Proxy at deployment time with a command similar to the following. Then configure CORS in the upstream API. Read about the [API Route Configuration](https://curity.io/resources/learn/aws-oauth-proxy/#configure-api-routes) details in the main tutorial.

```bash
aws lambda create-function --function-name ExampleAuthorizer \
--runtime java17 --handler io.curity.identityserver.tokenhandler.proxy.aws.ProcessCookie \
--environment "Variables={TOKEN_HANDLER_COOKIE_KEY=<key>,TOKEN_HANDLER_COOKIE_KEY_PASSWORD=<pass>}" \
--role <role-arn> \
--zip-file fileb://token-handler-proxy-authorizer-<version>.zip
```

**Azure API Management**

For Azure API Management, configure the OAuth Proxy at deployment time with a command similar to the following. Then configure CORS as a separate policy against the API route. Read about the [API Route Configuration](https://curity.io/resources/learn/azure-api-management-oauth-proxy/#configure-api-routes) details in the main tutorial.

```bash
az login
az deployment group create --resource-group <name-of-resource-group> \
  --template-file lib/configure.bicep \
  --parameters configure.bicepparam \
  --mode incremental
```

**Google Apigee**

For Google Apigee API Management, create policies for the OAuth Proxy and for CORS and then configure those policies as steps within the PreFlow of the ProxyEndpoint. Read more about the [API route configuration details](https://curity.io/resources/learn/google-apigee-oauth-proxy/#configure-api-routes) in the main tutorial.

```xml
<ProxyEndpoint name="default">
  <PreFlow name="default">
    <Request>
      <Step>
        <Name>Cors</Name>
      </Step>
      <Step>
        <Name>Set-Cookie-Key-From-KVM</Name>
      </Step>
      <Step>
        <Name>Token-Handler</Name>
      </Step>
    </Request>
  </PreFlow>
  ...
</ProxyEndpoint>
```

## Expose the OAuth Agent

The API gateway also provides the public URL for the OAuth Agent, at a path such as `/apps/example` within the token handler base URL. Create this route in the same way as API routes but do not configure any plugins, since the OAuth Agent implements its own cookie and CORS logic.

## Deploy a Local Gateway

You can also run a token handler on a local computer, to learn about how it works before deploying to real environments. You can run a local deployment using Docker, and expose the OAuth Agent and OAuth Proxy to a local SPA using domain based URLs. First, enable a local computer DNS solution to resolve host names. For example, add the following line to the `/etc/hosts` file.

```text
127.0.0.1 www.demoapp.example api.demoapp.example
```

Next, use Docker to deploy the token handler components. The following example shows a `docker-compose.yml` file that enables deployment of the Kong API gateway and the OAuth Agent. The `curity-config.xml` file would contain OAuth Agent configuration downloaded from the Admin UI, with a local development redirect URI such as `http://www.demoapp.example:3000/callback`. The `kong.yml` file would define development API routes and their use of the OAuth Prroxy and CORS plugins.

```yaml
services:
  kong:
    image: custom_kong:1.0.0
    ports:
      - 80:3001
    volumes:
      - ./kong.yml:/usr/local/kong/declarative/kong.yml
    environment:
      KONG_DATABASE: 'off'
      KONG_DECLARATIVE_CONFIG: '/usr/local/kong/declarative/kong.yml'
      KONG_PROXY_LISTEN: '0.0.0.0:3000'
      KONG_LOG_LEVEL: 'info'
      KONG_PLUGINS: 'bundled,cors,oauth-proxy'

  oauth-agent:
    image: curity.azurecr.io/curity/idsvr:latest
    hostname: oauthagent
    ports:
      - 6749:6749
    volumes:
      - ./license.json:/opt/idsvr/etc/init/license/license.json
      - ./curity-config.xml:/opt/idsvr/etc/init/curity-config.xml
    environment:
      ADMIN: 'true'
      LOGGING_LEVEL: 'INFO'
      BASE_URL: 'http://api.demoapp.example'
      PASSWORD: 'zIf66A9Wz'
```

The [Token Handler Deployment Example](https://curity.io/resources/learn/token-handler-deployment-example/) provides a reference deployment and it is possible to [Adapt the Deployment](https://curity.io/resources/learn/token-handler-deployment-example/#adapt-the-deployment) in various ways. For example, you can upgrade to an HTTPS development setup using locally issued OpenSSL certificates, or run a same-origin deployment where the OAuth Agent and OAuth Proxy run on the web origin and might use base URLs of the following form:

-   OAuth Agent Base URL: `https://www.demoapp.example/apps/example`
-   OAuth Proxy Base URL: `https://www.demoapp.example/api`

## Integrate the SPA

Once the API gateway work is complete, the SPA can call the token handler's external URLs. The final task is to [Integrate the SPA](https://curity.io/resources/learn/token-handler-integrate-spa/) so that it runs an OAuth flow and then calls APIs with secure cookies as credentials.
