---
title: "Kong OAuth Proxy Plugin"
description: "An OAuth proxy module that runs in the Kong API gateway, to translate secure cookies to access tokens"
url: "https://curity.io/resources/learn/kong-oauth-proxy/"
date: "2024-06-13"
area: "tutorials"
topic: "howtos"
pagegroup: "oauth-proxy-integration"
---

# Kong OAuth Proxy Plugin

The OAuth Proxy is an extension to your API gateway that you need when your single page applications (SPAs) call OAuth-secured APIs using [the Token Handler pattern](https://curity.io/resources/learn/the-token-handler-pattern/). The SPA sends an encrypted proxy cookie that transports an access token. The OAuth Proxy plugin decrypts the cookie to extract the access token.

When the OAuth Proxy work completes, your Kong API gateway routes the request to the target API, which uses the access token to implement its OAuth security.

## Download the OAuth Proxy

You get the OAuth Proxy by downloading the latest ZIP file version from the [Curity Developer Portal](https://developer.curity.io/releases/token-handler?proxy=kong), with a filename of the following form. This zip file contains a Lua plugin that you deploy to your gateway and a README file with detailed instructions.

```text
curity-token-handler-proxy-kong-<version>.zip
```

## Deploy the OAuth Proxy

You must deploy the OAuth Proxy to a gateway that runs in your SPA's backend for frontend domain. If a deployment uses the following URLs, the OAuth Proxy executes in a gateway at `https://bff.product.example`:

-   SPA Web Origin: `https://www.product.example`
-   Backend for Frontend Base URL: `https://bff.product.example`
-   Target API Base URL: `https://api.example.com`

To deploy the OAuth Proxy and its dependencies, use the luarocks file provided. One way to deploy the files is to create a custom Docker image:

```dockerfile
FROM kong/kong:3.8-ubuntu

COPY plugin/* \
    /tmp/oauth-proxy/
RUN cd /tmp/oauth-proxy && luarocks make oauth-proxy-*.rockspec \
    && cd / && rm -r /tmp/oauth-proxy

USER kong
```

Build the custom Docker image with a command such as the following:

```bash
docker build -t custom_kong:1.0.0 .
```

The luarocks command deploys Lua files to the Lua plugins location, which is a path similar to the following:

```text
/usr/local/share/lua/5.1/kong/plugins/oauth-proxy/
```

When you deploy the Kong gateway you must also activate plugins using the `KONG_PLUGINS` environment variable. For an example, study the following Docker Compose file:

```yaml
services:
  api-gateway:
    image: custom_kong:1.0.0
    hostname: apigateway-internal
    ports:
      - 80:3001
    volumes:
      - ./apigateway/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:3001'
      KONG_LOG_LEVEL: 'info'
      KONG_PLUGINS: 'bundled,cors,oauth-proxy'
```

## Prepare Decryption

You need an asymmetric keypair as part of your overall token handler deployment. To create one, follow the instructions in the `Configure Cryptographic Keys` section of the [Create a Token Handler](https://curity.io/resources/learn/curity-token-handler/#configure-cryptographic-keys) tutorial. This results in a PKCS#8 file with an encrypted private key, and also a private key password.

## Configure API Routes

You must configure the OAuth Proxy for all API routes that the SPA calls. Also, add a route such as `/oauthuserinfo` if the SPA calls the authorization server's OpenID Connect userinfo endpoint.

To configure the OAuth Proxy plugin you must provide the cookie decryption key for the OAuth Proxy, using the content of the PKCS#8 file and the PKCS#8 file's password.

```yaml
- name: example-api
  url: http://api-internal:3001
  routes:
  - name: example-api-route
    hosts:
    - bff.product.example
    paths:
    - /api
  plugins:
  - name: oauth-proxy
    config:
      cookie_key: |-
        -----BEGIN ENCRYPTED PRIVATE KEY-----
        MIH0MF8GCSqGSIb3DQEFDTBSMDEGCSqGSIb3DQEFDDAkBBA9BLL4kbxiN4dOlIZE
        nxxsAgIIADAMBggqhkiG9w0CCQUAMB0GCWCGSAFlAwQBKgQQ72a5HguvLkDUto5Q
        gLjuygSBkCOR6pSeXPp1ym5f+oPwYzT99EXbyxELUI43r01IcfY1i8Ib+rPbHB0K
        abRjKb/MnJXaRVS3iaQDYmTLK4SF6YcA3wRJtUZWTeCr79PbzkAootHyRjrYT6jN
        hOm/DLJHiRtNFyRTX+E9r9uMnYACmv6o0lsWScb0NrwPlyW3Ft14ayibtRvCnpEa
        CB3FgLlR9w==
        -----END ENCRYPTED PRIVATE KEY-----
      cookie_key_pass: Password1
```

The `cookie_key` and  `cookie_key_pass` configuration parameters are [referenceable values](https://docs.konghq.com/gateway/latest/kong-enterprise/secrets-management/), so you can also provide them in alternative ways. For example, the Docker Compose deployment could supply the values in `TH_COOKIE_KEY` and `TH_COOKIE_KEY_PASS` environment variables that are referenced in the API routes:

```yaml
- name: example-api
  url: http://api-internal:3001
  routes:
  - name: example-api-route
    hosts:
    - bff.product.example
    paths:
    - /api
  plugins:
  - name: oauth-proxy
    config:
      cookie_key: '{vault://env/th_cookie_key}'
      cookie_key_pass: '{vault://env/th_cookie_key_pass}'
```

Additional configuration settings are also available. For example, if the OAuth Agent uses a different prefix for cookie names than the default value `th-`, you should configure a `cookie_prefix` in the OAuth Proxy that matches the value from the OAuth Agent. You can find full information on configuration settings in the README file within your downloaded ZIP file, including some advanced options for caching.

## Configure CORS

When you use a [cross origin deployment](https://curity.io/resources/learn/token-handler-deployment-patterns/#token-handler-deployment-scenarios) you must also configure Cross-Origin Resource Sharing (CORS) to instruct the browser to only allow the SPA's precise web origin to send cookies. You can configure a CORS implementation of your choice, such as the built-in [CORS Plugin](https://docs.konghq.com/hub/kong-inc/cors/). An example that uses it is shown here.

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

When you configure CORS you should understand plugin priorities, since higher priorities execute first. In particular, the CORS plugin must run with a higher priority than the OAuth Proxy plugin. If the OAuth Proxy returns an error response, the CORS plugin adds the `access-control-allowed-origin` response header that enables the SPA to read error details.

| Plugin | Priority |
| --- | --- |
| CORS | 2000 |
| OAuth Proxy | 1900 |
| Phantom Token | 1000 |

## OAuth Proxy Output

At runtime, the OAuth Proxy processes cookies in incoming requests from SPAs. On success it rewrites the HTTP request, setting the access token in the HTTP authorization header. The target API then receives a JWT access token in the standard way and can use it for its authorization.

If the OAuth Proxy experiences an invalid cookie error, it returns an error response to the SPA with a 401 HTTP status code. For other types of error, the OAuth Proxy returns a 500 HTTP status code.

## Example Deployment

You can follow the [Token Handler Deployment Example](https://curity.io/resources/learn/token-handler-deployment-example/) to fully understand how the OAuth Proxy integrates into an SPA and API solution. The tutorial deploys an example Single Page Application that calls an example API through the OAuth Proxy. You can run the end-to-end example on a development computer with various configurations.

## Conclusion

The OAuth Proxy is part of your API gateway. It enables your SPAs to use the correct browser security and also make direct calls to API URLs. The OAuth Proxy plugin deals with the cookie complexity so that you do not need to implement it in your API code.
