Protect the API with an apikey

Now that we have our gateway in front of the API we can use it to enforce a first level of security. This will be to restrict access to the API to users who know the apikey.

Add and configure the plugin

Everything that can be done with an API in Kong (e.g. protecting it with an apikey) is done by plugins. So we will have to add the key-auth plugin to the service:

    plugins:
      - name: key-auth

The key-auth plugin requires a consumer that has a key. We can create these resources with the following lines in our configuration file:

The consumer doesn’t belong to the service, so it is not nested in the service resource (no indentation).

consumers:
  - username: api-user
    keyauth_credentials:
      - key: secret_key

The secret_key, as its name implies, is a value that should be kept secret. For this tutorial its ok to have it in plane text. Keep in mind to protect all your secrets properly for any publicly reachable environment.

Call the API

After starting the services we still can’t access our API with our (cURL-)commands. But this time we receive the following response from Kong:

{
  "message":"No API key found in request"
}

So from now on we will have to send the header apikey with every request to our API. The value of the header has to be secret_key. For the GET request to receive the list of existing rovers the command will look like this:

curl -X GET \
  http://localhost/rovers \
  -H 'apikey: secret_key'

Stop the services

In the next step we will make changes to our docker-compose.yaml file again. So you will need to stop the services.