Skip to content

Latest commit

 

History

History
976 lines (729 loc) · 30.6 KB

README.md

File metadata and controls

976 lines (729 loc) · 30.6 KB
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







How It Works

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



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:


Parameter Description Default Type Required
authenticationHeader Pass token using Authentication Header true bool ⚠️ Note
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 ⚠️ Note
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 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: