How-tos

8 mins read

Adding Authorization to APIs on Kong API Gateway with Docker

Learn how to apply access control to protect APIs deployed behind Kong API Gateways. Install necessary plugins in your Gateway. Deploy Cloudentity's Kong Authorizer to enforce policies applied to your discovered APIs.

Kong Gateway Integration using Docker

To learn in details about Kong Gateway, Cloudentity Kong Plugin, Kong Authorizer, and how the integration works, get familiar with:

Deploy Kong and Authorizer with Docker

The sections below explain how to set up Kong Gateway and Kong Authorizer using Docker.

Prerequisites

  1. Docker v1.19+ and Docker Compose installed for Docker-Based Kong Deployments.

  2. Access to an Cloudentity SaaS tenant

  3. Service to be protected by Kong Authorizer is deployed (this instruction allows you to deploy a mock service for testing purposes).

Build Kong with Cloudentity Kong Plugin Using Docker

  1. Clone the docker-kong project.

  2. Add the following steps to your Kong Gateway’s Dockerfile to make sure the kong-acp-plugin is installed.

    USER root
    
    RUN apk add gcc musl-dev
    
    RUN  luarocks install kong-plugin-acp
    

    As a result, the content in the customize/Dockerfile file should look similar to the following:

    ARG KONG_BASE=kong:2.8
    
    FROM ${KONG_BASE} AS build
    
    ARG PLUGINS
    ENV INJECTED_PLUGINS=${PLUGINS}
    
    ARG TEMPLATE=empty_file
    ENV TEMPLATE=${TEMPLATE}
    
    ARG ROCKS_DIR=empty_file
    ENV ROCKS_DIR=${ROCKS_DIR}
    
    ARG KONG_LICENSE_DATA
    ENV KONG_LICENSE_DATA=${KONG_LICENSE_DATA}
    
    COPY $TEMPLATE /custom_nginx.conf
    COPY $ROCKS_DIR /rocks-server
    COPY packer.lua /packer.lua
    
    USER root
    
    RUN /usr/local/openresty/luajit/bin/luajit /packer.lua -- "$INJECTED_PLUGINS"
    
    FROM ${KONG_BASE}
    
    USER root
    
    RUN apk add gcc musl-dev
    
    RUN  luarocks install kong-plugin-acp
    
    # Workarounds used:
    #  1 - the "custom_nginx.conf*" wildcard ensures it doesn't fail if it doesn't exist
    #  2 - "RUN true", see https://stackoverflow.com/questions/51115856/docker-failed-to-export-image-failed-to-create-image-failed-to-get-layer/62409523#62409523
    
    # replace the entrypoint, add the custom template if it exists
    COPY --from=build /docker-entrypoint.sh /old-entrypoint.sh /custom_nginx.conf* /
    RUN true
    
    # add the Lua files (.lua)
    COPY --from=build /usr/local/share/lua/5.1 /usr/local/share/lua/5.1
    RUN true
    
    # add the compiled libraries (.so)
    COPY --from=build /usr/local/lib/lua/5.1 /usr/local/lib/lua/5.1
    RUN true
    
    # add the Luarocks manifest
    COPY --from=build /usr/local/lib/luarocks/rocks-5.1 /usr/local/lib/luarocks/rocks-5.1
    RUN true
    
    HEALTHCHECK --interval=10s --timeout=10s --retries=10 CMD kong health
    
    USER kong
    
  3. In terminal, navigate to the /customize directory within your cloned project and build your image with the following command:

    docker build \
    --build-arg PLUGINS="kong-http-to-https,kong-upstream-jwt,kong-plugin-acp" \
    --build-arg "KONG_LICENSE_DATA=$KONG_LICENSE_DATA" \
    --tag "kong-acp" .
    

    Tip

    As you can see in the command above, the kong-plugin-acp is included in the PLUGINS build argument for your image. You can, of course, define more plugins for your deployment here. After the scripts from the Dockerfile are executed, the kong-plugin-acp is installed within your image and kong-plugin-acp is present in the list of your plugins in the kong.conf file for your Docker deployment.

Once your image is ready and built, you can deploy it to a container, expose services, and add routes to them.

Deploy Kong with Cloudentity Plugin

Use the following Kong documents to quickly deploy Kong Gateway and attach a service and route to it.

  • For detailed instructions on how to run Docker images for Kong Gateway working with a PostgreSQL database, visit Install Kong Gateway on Docker

    If you chose to build your image as shown in the examples above, keep in mind that the image from the example above is tagged kong-acp, so please adapt the example from Kong docs accordingly. Also, with the instructions from KongHQ you create a network for your Docker containers. Keep in mind that all componenets - Kong Gateway, Kong Authorizer, as well as your service, must run on the same network.

  • To learn how to expose services and add routes on a mock service, see the Expose your Services with Kong Gateway documentation. If you already have a service, make sure it’s on the correct Docker network.

Kong Docker Images

For technical details on Docker images for Kong Gateway, visit:

Assign Cloudentity Kong Plugin to Service

Having deployed Kong Gateway and a service, it’s time to assign the Cloudentity Kong Plugin to your service, use the Kong Gateway Admin API:

curl -sSk -X POST https://{ADMIN-URL}/services/{NAME-OF-YOUR-SERVICE}/plugins \
     --data 'name=acp' \
     --data 'config.api_group_id={ID-OF-YOUR-API-GROUP}' \
     --data 'config.auth_url=https://kong-authorizer:9003/authorize'

Protected Kong Admin API

If Kong Admin API is protected, the request must be correctly authenticated. For more information, read Authenticating to the Kong Admin API.

As you can see, the curl request contains the following variables:

  • {ADMIN-URL} which should point to the URL of your Kong Gateway Admin API

  • {NAME-OF-YOUR-SERVICE} which should point to the name of the service to which you wish to assign the plugin

  • {ID-OF-YOUR-API-GROUP} which should point to the identifier of your API group in Kong Gateway

The request also contains the --data 'name=acp' argument, which is assigns the acp plugin to the service. Additionally, it contains also the --data 'config.auth_url=https://kong-authorizer:9003/authorize' argument which points to the URL under which your Kong Authorizer will be running.

Below, you can find an example of a request that assigns the acp plugin to an httpbin service exposed by a locally deployed Kong Gateway:

curl -sSk -X POST http://localhost:8001/services/httpbin-service/plugins \
     --data 'name=acp' \
     --data 'config.api_group_id=httpbin-service' \
     --data 'config.auth_url=https://kong-authorizer:9003/authorize'

Declarative Configuration for DB-less Setup

If your Kong Gateway is running without a database, you can use declarative configuration for your service to assign the acp plugin to your service as illustrated below:

services:
- name: httpbin-service
   url: https://httpbin.org
   routes:
   - name: anything
      hosts: [ "httpbin.org" ]
      paths: [ "/anything" ]
      methods: [ "GET", "PATCH", "PUT", "POST", "DELETE" ]
      strip_path: false
   plugins:
   - name: acp
      config:
      api_group_id: httpbin-service
      auth_url: https://kong-authorizer:9003/authorize

Create Kong Authorizer in Cloudentity

Before deploying Kong Authorizer, you must create it in Cloudentity.

  1. In your Cloudentity tenant, go to the workspace of your choice.

  2. Select Authorization » Gateways » CREATE GATEWAY » Kong.

  3. Provide a name and a description for your Kong Authorizer.

  4. Optionally, enable the Create and bind services automatically check box.

    Tip

    When enabled, all services protected by your Kong Authorizer instance are discovered and added to the Cloudentity service list automatically when the Kong authorizer is connected to Cloudentity. Otherwise, you need to add them manually.

  5. Follow the Quick Start instruction. Download the package for your Authorizer and check the instructions in the section below.

Deploy Kong Authorizer using Docker

  1. Unzip the package with the downloaded Kong Authorizer.

  2. In the .env file, set the KONG_ADMIN_URL to the URL of your Kong Admin API.

    Tip

    If you are testing it locally in your Docker deployment, the URL contains the name of the container where your Kong Gateway is running and the port number like shown below:

    KONG_ADMIN_URL=http://kong-acp:8001

    Note that, by default, the port for HTTPS connection to the Kong Admin API is 8444.

  3. In the terminal, navigate to the directory with your Kong Authorizer and execute the following commands:

    cat credentials.txt | docker login docker.cloudentity.io --username acp --password-stdin
    

    and

    docker-compose up
    

    The first command logins to Cloudentity docker with the credentials provided in the credentials.txt file in your Kong Authorizer package.

    The docker-compose up spins up a Docker container with the Kong Authorizer for you. In the logs for the Kong Authorizer, you should see that it starts the authorizer reload. At this point, however, your authorizer is not yet running in the same network as your Kong Gateway, so it is not possible for the authorizer to communicate with the gateway.

  4. Connect your authorizer to the same network that your Kong Gateway uses.

    In general, you can use a method of your choice to connect your authorizer to the network. You can, for example, execute the following command when the container with your Kong Authorizer is running:

    docker network connect {network} {container}
    

    For example: docker network kong-network 1babdf8b72a6

    Result

    Once the authorizer is successfully assigned to the same network as your gateway, you can see in the authorizer’s logs that the authorization configuration was reloaded.

    In Cloudentity APIs Management View, you can see APIs that were discovered by your Kong Authorizer. You can now apply access control to them.

Apply Sample Policy

  1. In Cloudentity, create a policy.

  2. Go to Enforcement > APIs > AUTHORIZATION.

  3. Select a service protected by the Kong Authorizer and any API with authorization status Unrestricted.

  4. In the Edit API popup window, select Policy from the list and click Update to proceed.

Result

You have successfully assigned a policy to your API.

Test Kong Gateway Integration

To test if your integration was successful and that your APIs are protected, you can, for example, create a simple Cloudentity or REGO policy that will always pass. Call your protected endpoint (below, it’s /anything) and check if the response is successful.

Connected APIs

You can see which APIs are protected by your Kong authorizer by checking under Enforcement > Authorizers > YOUR_KONG_AUTHORIZER > APIs.

curl -i --request GET http://localhost:8000/anything

If the request is succesful, change your policy so that it blocks APIs. The next request to your protected endpoint should be blocked with the unauthorized access error.

Configure Kong Authorizer

For all available and up-to-date configuration options, see Kong Authorizer Configuration Reference.

The Kong Authorizer can be configured with a file in YAML format, or via environment variables. To generate a template configuration file that is populated with default settings, you can use a Docker image and pipe the output to a configuration file:

docker run --rm docker.cloudentity.io/kong-authorizer reference > reference_config.yaml

You can use the reference configuration as a basis for your customization. You can omit settings for which the default configuration is satisfactory, specifying only the required values, which are the client ID, client secret, issuer URL, and Kong admin URL parameters.

ACP_CLIENT_ID: { your_client_id }
ACP_CLIENT_SECRET: { your_client_secret }
ACP_ISSUER_URL: https://{tid}.us.authz.stage.cloudentity.io/{tid}/system
KONG_ADMIN_URL: http://kong-acp:8001

Environment variables can also be used to set these configuration values. The environment variable’s name are the uppercase version of the YAML name. For example, in the docker-compose.yml that you downloaded, you can set the ACP_CLIENT_ID via the environment variable ACP_CLIENT_ID:

environment:
  - ACP_CLIENT_ID=${CLIENT_ID}
  - ACP_CLIENT_SECRET=${CLIENT_SECRET}
  - ACP_ISSUER_URL=${ISSUER_URL}
  - ACP_HTTP_CLIENT_INSECURE_SKIP_VERIFY=TRUE
  - KONG_ADMIN_URL=${KONG_ADMIN_URL}
  - KONG_HTTP_CLIENT_INSECURE_SKIP_VERIFY=TRUE
  - SERVER_LISTENER_PORT=9003

Tip

Note that nested YAML settings can be accessed by joining uppercased names with underscores, as shown in the example above, where the SERVER_LISTENER_PORT=9003 parameter is set.

To run the kong authorizer with a configuration file, use the --config option to specify the YAML file with your configuration. For example, assuming that you have created a kong_config.yaml file in your current directory your docker run command would look like the following:

docker run --rm --volume `pwd`:/config:ro docker.cloudentity.io/kong-authorizer --config /config/kong_config.yaml
Updated: Nov 9, 2023