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 (e.g. protecting it with an apikey) is done by using plugins. So we will have to add the key-auth plugin to the service by running the following command:

curl -X POST \
  http://localhost:8001/services/rover-api/plugins \
  -H 'Content-Type: application/json' \
  -d '{
	"name": "key-auth"
}'

The key-auth plugin requires a consumer that has a key. We can create these resources with the following commands:

curl -X POST \
  http://localhost:8001/consumers \
  -H 'Content-Type: application/json' \
  -d '{
	"username": "api-user"
}'
curl -X POST \
  http://localhost:8001/consumers/api-user/key-auth \
  -H 'Content-Type: application/json' \
  -d '{
	"key": "secret_key"
}'

Call the API

When we use our (cURL-)commands again, our request will not be forwarded to the API. Instead the API gateway will send the following response:

{
  "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 again:

docker-compose down