/API Key & Token Middleware

API Key & Token Middleware

5
v0.1.4
Traefik v3 middleware which allows for you to protect certain aspects of your site with an API token.

♾️ Traefik API Key & Token Middleware ♾️


This Traefik middleware allows you to secure certain routes behind a request header API token. Users who have not successfully authenticated will be greeted with a 403 Forbidden Error. Also displays information about each connection including IP address and URL that the user is trying to access.




Version Downloads Build Status Size Last Commit Contributors

Built with Material for MkDocs







Configuration

The following provides examples for usage scenarios.


Static File

If you are utilizing a Traefik Static File, review the following examples:


File (YAML)

## Static configuration
experimental:
plugins:
traefik-api-token-middleware:
moduleName: "github.com/Aetherinox/traefik-api-token-middleware"
version: "v0.1.4"

File (TOML)

## Static configuration
[experimental.plugins.traefik-api-token-middleware]
moduleName = "github.com/Aetherinox/traefik-api-token-middleware"
version = "v0.1.4"

CLI

## Static configuration
--experimental.plugins.traefik-api-token-middleware.modulename=github.com/Aetherinox/traefik-api-token-middleware
--experimental.plugins.traefik-api-token-middleware.version=v0.1.4

Dynamic File

If you are utilizing a Traefik Dynamic File, review the following examples:


File (YAML)

# Dynamic configuration
http:
middlewares:
api-token:
plugin:
traefik-api-token-middleware:
authenticationHeader: true
authenticationHeaderName: X-API-TOKEN
authenticationErrorMsg: "Invalid token"
bearerHeader: true
bearerHeaderName: Authorization
removeHeadersOnSuccess: true
removeTokenNameOnFailure: false
timestampUnix: false
permissiveMode: false
debugLogs: false
agentDeny:
- '\buseragent1\b'
agentAllow:
- '\buseragent2\b'
tokens:
- your-api-token
whitelistIPs:
- '66.85.101.2'
- '10.10.0.7/32'

File (TOML)

# Dynamic configuration
[http]
[http.middlewares]
[http.middlewares.api-token]
[http.middlewares.api-token.plugin]
[http.middlewares.api-token.plugin.traefik-api-token-middleware]
authenticationHeader = true
authenticationHeaderName = "X-API-TOKEN"
authenticationErrorMsg = "Invalid token"
bearerHeader = true
bearerHeaderName = "Authorization"
removeHeadersOnSuccess = true
removeTokenNameOnFailure = false
timestampUnix = false
permissiveMode = false
debugLogs = false
agentDeny = ["\buseragent1\b"]
agentAllow = ["\buseragent2\b"]
tokens = ["your-api-token"]
whitelistIPs = ["66.85.101.2", "10.10.0.7/32"]

Kubernetes Custom Resource Definition

# Dynamic configuration
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
name: api-token
spec:
plugin:
traefik-api-token-middleware:
authenticationHeader: true
authenticationHeaderName: X-API-TOKEN
authenticationErrorMsg: "Invalid token"
bearerHeader: true
bearerHeaderName: Authorization
removeHeadersOnSuccess: true
removeTokenNameOnFailure: false
timestampUnix: false
permissiveMode: false
debugLogs: false
agentDeny:
- '\buseragent1\b'
agentAllow:
- '\buseragent2\b'
tokens:
- your-api-token



Parameters

This plugin accepts the following parameters:


ParameterDescriptionDefaultTypeRequired
authenticationHeaderPass token using Authentication Headertruebool⚠️ Note
authenticationHeaderNameAuthentication header name'X-API-TOKEN'string⭕ Optional
authenticationErrorMsgError message to display on unsuccessful authentication'Access Denied'string⭕ Optional
bearerHeaderPass token using Authentication Header Bearer Keytruebool⚠️ Note
bearerHeaderNameAuthentication bearer header name'Authorization'string⭕ Optional
tokensList of API tokens[][]string✔️ Required
removeHeadersOnSuccessIf true; remove header on successful authenticationtruebool⭕ Optional
removeTokenNameOnFailureDon't display name of token in unsuccessful error messagefalsebool⭕ Optional
timestampUnixDisplay datetime in Unix timestamp instead of UnixDatefalsebool⭕ Optional
whitelistIPsA list of IP blocks that will bypass the api-token check[][]string⭕ Optional
agentDenyBlacklist list of useragents from accessing routes
Stacks on top of the authorization token
[][]string⭕ Optional
agentAllowWhitelist list of useragents to access routes
Stacks on top of the authorization token
[][]string⭕ Optional
permissiveModeExecute a dry-run, allows access even if a token is invalidfalsebool⭕ Optional
debugLogsShows debug logs in consolefalsebool⭕ Optional

  • ⚠️: Plugin requires that you enable either authenticationHeader OR bearerHeader. One of the two MUST be enabled.

authenticationHeader

If enabled, will use an Authentication Header to pass a token. If you set this to true, you must ensure the following are also configured:

  • authenticationHeaderName
  • tokens

If you do not wish to use the authentication header, you can alternatively use the bearerHeader.



authenticationErrorMsg

This setting changes the text at the beginning of an error message when an invalid token is specified.


authenticationErrorMsg:

{
"message": "Access Denied. Provide a valid API Token header using either X-API-TOKEN: $token or Authorization: Bearer $token",
"status_code": 403,
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0",
"ip": "XX.XX.XX.XX",
"host": "sub.domain.lan",
"uri": "/",
"timestamp": "Fri Sep 27 03:24:27 UTC 2024"
}

authenticationErrorMsg: "You cannot access this API"

{
"message": "You cannot access this API. Provide a valid API Token header using either X-API-TOKEN: $token or Authorization: Bearer $token",
"status_code": 403,
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0",
"ip": "XX.XX.XX.XX",
"host": "sub.domain.lan",
"uri": "/",
"timestamp": "Fri Sep 27 03:24:27 UTC 2024"
}


bearerHeader

If enabled, will use an Bearer Header to pass a token. If you set this to true, you must ensure the following are also configured:

  • bearerHeaderName
  • tokens

If you do not wish to use the authentication header, you can alternatively use the authenticationHeader.



tokens

A list of tokens that will accepted for each authentication.


# Dynamic configuration
http:
middlewares:
api-token:
plugin:
traefik-api-token-middleware:
authenticationHeader: true
authenticationHeaderName: X-API-TOKEN
tokens:
- your-api-token
- second-api-token


removeHeadersOnSuccess

If set true, the authentication / bearer header will be removed upon successful authentication. Works with both the authenticationHeader and bearerHeader.



removeTokenNameOnFailure

This setting changes how error messages are displayed to a user who doesn't provide a correct token. If enabled, it will keep the name of your token private.


removeTokenNameOnFailure: true

{
"message": "Access Denied. Provide a valid API Token header using either X-API-TOKEN: $token or Authorization: Bearer $token",
"status_code": 403,
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0",
"ip": "XX.XX.XX.XX",
"host": "sub.domain.lan",
"uri": "/",
"timestamp": "1727432498"
}

removeTokenNameOnFailure: false

{
"message": "Access Denied.",
"status_code": 403,
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0",
"ip": "XX.XX.XX.XX",
"host": "sub.domain.lan",
"uri": "/",
"timestamp": "1727432498"
}


timestampUnix

This setting changes how the date / time will be displayed in your API callback / output.


timestampUnix: true

{
"message": "Access Denied. Provide a valid API Token header using either X-API-TOKEN: $token or Authorization: Bearer $token",
"status_code": 403,
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0",
"ip": "XX.XX.XX.XX",
"host": "sub.domain.lan",
"uri": "/",
"timestamp": "1727432498"
}

timestampUnix: false

{
"message": "Access Denied. Provide a valid API Token header using either X-API-TOKEN: $token or Authorization: Bearer $token",
"status_code": 403,
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0",
"ip": "XX.XX.XX.XX",
"host": "sub.domain.lan",
"uri": "/",
"timestamp": "Fri Sep 27 03:24:27 UTC 2024"
}


whitelistIPs

Allows you to specify a list of whitelisted IP addresses that will not have the API-token checked.


# Dynamic configuration
http:
middlewares:
api-token:
plugin:
traefik-api-token-middleware:
authenticationHeader: true
authenticationHeaderName: X-API-TOKEN
authenticationErrorMsg: 'Invalid token'
tokens:
- your-api-token
whitelistIPs:
- '66.85.101.2'
- '10.10.0.7/32'


agentDeny

Specifies a list of useragents that are NOT allowed to access your protected routes. This setting stacks on top of the Authentication or Bearer Token. If the user has the correct token, but is listed in this deny list; they will be blocked from accessing anything. Utilizes Golang regex rules.


# Dynamic configuration
http:
middlewares:
api-token:
plugin:
traefik-api-token-middleware:
authenticationHeader: true
authenticationHeaderName: X-API-TOKEN
agentDeny:
- '\buseragent1\b'


agentAllow

Specifies a list of useragents that are allowed to access your protected routes. This setting stacks on top of the Authentication or Bearer Token. If the user has the correct token, but is not in this allow list; they will be blocked from accessing anything. Utilizes Golang regex rules.


# Dynamic configuration
http:
middlewares:
api-token:
plugin:
traefik-api-token-middleware:
authenticationHeader: true
authenticationHeaderName: X-API-TOKEN
agentAllow:
- '\buseragent2\b'


permissiveMode

Allows to execute a dry-run on a request. The request will pass successfully even if the API token is invalid. Used for testing.

# Dynamic configuration
http:
middlewares:
api-token:
plugin:
traefik-api-token-middleware:
authenticationHeader: true
authenticationHeaderName: X-API-TOKEN
permissiveMode: true


debugLogs

If set true, gives you a more detailed outline of what is going on behind the scenes in your console.




Full Examples

A few extra examples have been provided.


http:
middlewares:
api-token:
plugin:
traefik-api-token-middleware:
authenticationHeader: true
authenticationHeaderName: X-API-TOKEN
authenticationErrorMsg: "Invalid token"
bearerHeader: true
bearerHeaderName: Authorization
removeHeadersOnSuccess: true
removeTokenNameOnFailure: false
timestampUnix: false
permissiveMode: false
debugLogs: true
tokens:
- your-api-token
routers:
traefik-http:
service: "traefik"
rule: "Host(`yourdomain.com`)"
entryPoints:
- http
middlewares:
- https-redirect@file
traefik-https:
service: "traefik"
rule: "Host(`yourdomain.com`)"
entryPoints:
- https
middlewares:
- api-token@file
tls:
certResolver: cloudflare
domains:
- main: "yourdomain.com"
sans:
- "*.yourdomain.com"



Browser Plugins

If you do not want to specify an API token using conventional means (such as by using curl), you can utilize a front-end browser extension. This allows you to supply a modified request header with your specific API token which will grant you access to your desired location.


Firefox

If you are using Firefox, install the plugin(s) below. ( Pick One ):


Extension: Header Editor

With this extension, you can modify the request header and response header, cancel a request and redirect a request. Please do not write regular expressions that begin with (. *), (. *?), (. +), such regular expressions may cause problems with Firefox


Once you install the browser extension above, open the settings.



Create a new rule

  • Name: API Token
  • Rule Type: Modify request header
  • Match Type: Domain
    • Match Rules: subdomain.domain.com
    • Exclude Rule: none
  • Execute Type: normal
    • Header Name: x-api-token
    • Header Value: your-api-token


Once you have your modified header added to the browser extension, verify it by reading the section Verifying Modified Headers.



Extension: Modify Header Value

Modify Header Value can add, modify or remove an HTTP-request-header for all requests on a desired website or URL. This Firefox add-on is very useful if you are an App developer, website designer, or if you want to test a particular header for a request on a website.


Once you install the browser extension above, open the settings.



You need to add a new rule which injects your modified header into the specified domain.



Once you have your modified header added to the browser extension, verify it by reading the section Verifying Modified Headers.




Verifying Modified Headers

This section explains how you can verify that your modified request header is being received by your server.

Access the subdomain where you have applied an API-TOKEN. Once the page loads, open the Developer Console.

  • Firefox: SHIFT + CTRL + I
  • Chrome: SHIFT + CTRL + I
  • Safari: Option + ⌘ + C

A box should appear either on the right or bottom. Within the Console tab, ensure you have Errors, Warnings, Logs, Info, and Debug selected. They will have lines under them when enabled.



Next, refresh your browser's page.

  • Firefox: SHIFT + F5
  • Chrome: SHIFT + F5
  • Safari: OPTION + ⌘ + E


In the bottom box, you should see a list of actions, which display your domain name, a status code, and the number of milliseconds it took to perform the action.

01:00:25.139        GET https://sub.yourdomain.com                     [HTTP/2 403  1ms]

  • 403 status: API-TOKEN was not accepted.
  • 200 status: API-TOKEN was accepted. (along with being able to actually see your site)

Typically with a 403 status, you can click the box that contains the status code with your domain, which will expand a box and show you the headers that were passed to the site, including your API-TOKEN.



In the example above, we've passed BadToken which can be seen in the header response.




Local Install

Traefik comes with the ability to install this plugin locally without fetching it from Github.


Download a local copy of this plugin to your server within your Traefik installation folder.

git clone https://github.com/Aetherinox/traefik-api-token-middleware.git

If you are running Docker, you need to mount a new volume:


[!WARNING] The path to the plugin is case sensitive, do not change the casing of the folders, or the plugin will fail to load.


services:
traefik:
container_name: traefik
image: traefik:latest
restart: unless-stopped
volumes:
- ./traefik-api-token-middleware:/plugins-local/src/github.com/Aetherinox/traefik-api-token-middleware/

Static File

Open your Traefik Static File and change plugins to localPlugins.


File (YAML)

# Static configuration
experimental:
localPlugins:
traefik-api-token-middleware:
moduleName: "github.com/Aetherinox/traefik-api-token-middleware"
version: "v0.1.4"

File (TOML)

# Static configuration
[experimental.localPlugins.traefik-api-token-middleware]
moduleName = "github.com/Aetherinox/traefik-api-token-middleware"
version = "v0.1.4"

Dynamic File

For local installation, your dynamic file will contain the same contents as it would if you installed the plugin normally.


File (YAML)

# Dynamic configuration
http:
middlewares:
api-token:
plugin:
traefik-api-token-middleware:
authenticationHeader: true
authenticationHeaderName: X-API-TOKEN
authenticationErrorMsg: "Invalid token"
bearerHeader: true
bearerHeaderName: Authorization
removeHeadersOnSuccess: true
removeTokenNameOnFailure: false
timestampUnix: false
tokens:
- your-api-token

File (TOML)

# Dynamic configuration
[http]
[http.middlewares]
[http.middlewares.api-token]
[http.middlewares.api-token.plugin]
[http.middlewares.api-token.plugin.traefik-api-token-middleware]
authenticationHeader = true
authenticationHeaderName = "X-API-TOKEN"
authenticationErrorMsg = "Invalid token"
bearerHeader = true
bearerHeaderName = "Authorization"
removeHeadersOnSuccess = true
removeTokenNameOnFailure = false
timestampUnix = false
tokens = ["your-api-token"]



Contributors ✨

We are always looking for contributors. If you feel that you can provide something useful to Gistr, then we'd love to review your suggestion. Before submitting your contribution, please review the following resources:


Want to help but can't write code?


Alt


The following people have helped get this project going: