Traefik v3 middleware which allows for you to protect certain aspects of your site with an API token.
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.
- How It Works
- Configuration
- Parameters
- Full Examples
- Browser Plugins
- Verifying Modified Headers
- Local Install
- Contributors ✨
This middleware offers you the ability to restrict certain containers being routed through Traefik. You can restrict a container to be inaccessible unless a user does one of the following:
- Has a whitelisted IP address
- Provides a valid request header value:
X-API-TOKEN
- Uses a valid useragent when accessing that container through their browser.
When enabling multiple ways to access the container, remember that the options are One OR the other.
This means that if you whitelist a user's IP address, and also specify a useragent which is allowed to access your container; the user does NOT need to satisfy both requirements.
They either need to be using a whitelisted IP when making their connection, OR their useragent must be a particular value.
In other words, meeting one of multiple provided options, satisfies ALL options and grants the user permission to the container.
This ensures that if you have a vital container behind your security measures and you have an incident where your whitelisted IP address changes; you have a backup method to re-gain access.
If you opt to require a request header for X-API-TOKEN
, you should change the default header name to something else and not the default value. This ensures that outside users cannot start guessing your token.
authenticationHeaderName: X-CUSTOM-TOKEN-NAME
The following provides examples for usage scenarios.
If you are utilizing a Traefik Static File, review the following examples:
## Static configuration
experimental:
plugins:
traefik-api-token-middleware:
moduleName: "github.com/Aetherinox/traefik-api-token-middleware"
version: "v0.1.4"
## Static configuration
[experimental.plugins.traefik-api-token-middleware]
moduleName = "github.com/Aetherinox/traefik-api-token-middleware"
version = "v0.1.4"
## 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
If you are utilizing a Traefik Dynamic File, review the following examples:
# 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'
# 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"]
# 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
This plugin accepts the following parameters:
Parameter | Description | Default | Type | Required |
---|---|---|---|---|
authenticationHeader |
Pass token using Authentication Header | true | bool | |
authenticationHeaderName |
Authentication header name | 'X-API-TOKEN' | string | ⭕ Optional |
authenticationErrorMsg |
Error message to display on unsuccessful authentication | 'Access Denied' | string | ⭕ Optional |
bearerHeader |
Pass token using Authentication Header Bearer Key | true | bool | |
bearerHeaderName |
Authentication bearer header name | 'Authorization' | string | ⭕ Optional |
tokens |
List of API tokens | [] | []string | ✔️ Required |
removeHeadersOnSuccess |
If true ; remove header on successful authentication |
true | bool | ⭕ Optional |
removeTokenNameOnFailure |
Don't display name of token in unsuccessful error message | false | bool | ⭕ Optional |
timestampUnix |
Display datetime in Unix timestamp instead of UnixDate | false | bool | ⭕ Optional |
whitelistIPs |
A list of IP blocks that will bypass the api-token check | [] | []string | ⭕ Optional |
agentDeny |
Blacklist list of useragents from accessing routes Stacks on top of the authorization token |
[] | []string | ⭕ Optional |
agentAllow |
Whitelist list of useragents to access routes Stacks on top of the authorization token |
[] | []string | ⭕ Optional |
permissiveMode |
Execute a dry-run, allows access even if a token is invalid | false | bool | ⭕ Optional |
debugLogs |
Shows debug logs in console | false | bool | ⭕ Optional |
⚠️ : Plugin requires that you enable eitherauthenticationHeader
ORbearerHeader
. One of the two MUST be enabled.
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.
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"
}
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.
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
If set true
, the authentication / bearer header will be removed upon successful authentication. Works with both the authenticationHeader and bearerHeader.
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"
}
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"
}
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'
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'
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'
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
If set true
, gives you a more detailed outline of what is going on behind the scenes in your console.
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"
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.
If you are using Firefox, install the plugin(s) below. ( Pick One ):
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
- Match Rules:
- Execute Type:
normal
- Header Name:
x-api-token
- Header Value:
your-api-token
- Header Name:
Once you have your modified header added to the browser extension, verify it by reading the section Verifying Modified Headers.
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.
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.
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/
Open your Traefik Static File and change plugins
to localPlugins
.
# Static configuration
experimental:
localPlugins:
traefik-api-token-middleware:
moduleName: "github.com/Aetherinox/traefik-api-token-middleware"
version: "v0.1.4"
# Static configuration
[experimental.localPlugins.traefik-api-token-middleware]
moduleName = "github.com/Aetherinox/traefik-api-token-middleware"
version = "v0.1.4"
For local installation, your dynamic file will contain the same contents as it would if you installed the plugin normally.
# 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
# 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"]
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?
- Review active questions by our community and answer the ones you know.
The following people have helped get this project going: