Add Traefik Hub Middlewares To Reference Section

This commit is contained in:
Sheddy 2025-07-29 15:02:52 +01:00 committed by GitHub
parent 40bdea4db8
commit cf1e582af5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 1701 additions and 0 deletions

View File

@ -0,0 +1,58 @@
/* Traefik Hub Menu icon base styles */
.menu-icon {
height: 18px;
width: 18px;
vertical-align: middle;
margin-left: 6px;
transition: all 0.2s ease;
filter: drop-shadow(0 1px 1px rgba(0,0,0,0.1));
display: inline;
white-space: nowrap;
}
/* Ensure parent container keeps items inline */
.nav-link-with-icon {
white-space: nowrap !important;
display: inline-flex !important;
align-items: center !important;
}
/* Hover effects */
.menu-icon:hover {
transform: scale(1.05);
opacity: 0.8;
}
/* Tablet responsive */
@media (max-width: 1024px) {
.menu-icon {
height: 14px;
width: 14px;
margin-left: 4px;
}
}
/* Mobile responsive */
@media (max-width: 768px) {
.menu-icon {
height: 12px;
width: 12px;
margin-left: 3px;
vertical-align: middle;
}
/* Keep mobile navigation items inline */
.nav-link-with-icon {
display: inline-flex !important;
align-items: center !important;
width: auto !important;
}
}
/* High DPI displays */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
.menu-icon {
image-rendering: -webkit-optimize-contrast;
image-rendering: crisp-edges;
}
}

View File

@ -0,0 +1,56 @@
---
title: 'API Key Authentication'
description: 'Traefik Hub API Gateway - The API Key authentication middleware allows you to secure an API by requiring a secret key, base64 encoded or not, to be given, via an HTTP header, a cookie or a query parameter.'
---
!!! info "Traefik Hub Feature"
This middleware is available exclusively in [Traefik Hub](https://traefik.io/traefik-hub/). Learn more about [Traefik Hub's advanced features](https://doc.traefik.io/traefik-hub/api-gateway/intro).
The API Key authentication middleware allows you to secure an API by requiring a secret key, base64 encoded or not, to be given, via an HTTP header, a cookie or a query parameter.
---
## Configuration Example
```yaml tab="Middleware API Key"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-apikey
namespace: apps
spec:
plugin:
apiKey:
keySource:
headerAuthScheme: Bearer
header: Authorization
secretNonBase64Encoded: true
secretValues:
- "urn:k8s:secret:apikey:secret"
- "urn:k8s:secret:apikey:othersecret"
```
```yaml tab="Values Secret"
apiVersion: v1
kind: Secret
type: Opaque
metadata:
name: apikey
namespace: whoami
stringData:
secret: $2y$05$D4SPFxzfWKcx1OXfVhRbvOTH/QB0Lm6AXTk8.NOmU4rPLX2t6UUuW # htpasswd -nbB "" foo | cut -c 2-
othersecret: $2y$05$HbLL.g5dUqJippH0RuAGL.RaM9wNS2cT7hp6.vbv5okdCmVBSDzzK # htpasswd -nbB "" bar | cut -c 2-
```
## Configuration Options
| Field | Description | Default | Required |
|:-----------------------------|:------------------------------------------------|:--------|:---------|
| `keySource.header` | Defines the header name containing the secret sent by the client.<br /> Either `keySource.header` or `keySource.query` or `keySource.cookie` must be set. | "" | No |
| `keySource.headerAuthScheme` | Defines the scheme when using `Authorization` as header name. <br /> Check out the `Authorization` header [documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization#syntax). | "" | No |
| `keySource.query` | Defines the query parameter name containing the secret sent by the client.<br /> Either `keySource.header` or `keySource.query` or `keySource.cookie` must be set. | "" | No |
| `keySource.cookie` | Defines the cookie name containing the secret sent by the client.<br /> Either `keySource.header` or `keySource.query` or `keySource.cookie` must be set. | "" | No |
| `secretNonBase64Encoded` | Defines whether the secret sent by the client is base64 encoded. | false | No |
| `secretValues` | Contain the hash of the API keys. <br /> Supported hashing algorithms are Bcrypt, SHA1 and MD5. <br /> The hash should be generated using `htpasswd`.<br />Can reference a Kubernetes Secret using the URN format: `urn:k8s:secret:[name]:[valueKey]` | [] | Yes |
{!traefik-for-business-applications.md!}

View File

@ -0,0 +1,207 @@
---
title: "HMAC"
description: "Traefik Hub API Gateway - The HMAC Middleware allows you secure your APIs using the HMAC mechanism."
---
!!! info "Traefik Hub Feature"
This middleware is available exclusively in [Traefik Hub](https://traefik.io/traefik-hub/). Learn more about [Traefik Hub's advanced features](https://doc.traefik.io/traefik-hub/api-gateway/intro).
This middleware validates a digital signature computed using the content of an HTTP request and a shared secret that is
sent to the proxy using the `Authorization` or `Proxy-Authorization` header.
It ensures:
- **The identity of the sender (Authentication)**: If the signature is validated by the proxy, it means that the sender
actually owns the shared secret. As a consequence, the sender's identity is considered to be proven.
- **The integrity of the request**: As the signature is based on a subset of the HTTP request, it means that if the
signature is validated by the proxy, the request used to generate the signature has not been modified between the sender
and the proxy. This middleware also allows validating the content integrity using the
[Digest header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Digest).
This middleware is based on the [HTTP Signature Draft](https://datatracker.ietf.org/doc/html/draft-cavage-http-signatures-12).
---
## Configuration Example
Below is an advanced configuration that enables the HMAC middleware, sets one secret, ensures that the digest sum of the
request body is validated and ensures that the given headers must be included in the computation of the signature of the
request.
```yaml tab="Middleware HMAC"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: hmac-auth
spec:
plugin:
hmac:
keys:
- id: secret-key
key: secret
validateDigest: true
enforcedHeaders:
- (request-target)
- (created)
- (expires)
- host
```
## Configuration Options
| Field | Description | Default | Required |
|:------------------|:---------------------------------------------|:--------|:---------|
| `keys` | A static set of secret keys to be used by HMAC middleware. | | Yes |
| `validateDigest` | Determines whether the middleware should validate the digest sum of the request body. | true | No |
| `enforcedHeaders` | A set of headers that must be included in the computation of the signature of the request. | | No |
## Authentication Mechanism
The sender and proxy share a common secret identified by a `keyId`. How the sender gets the secret and keeps it safe is out of scope of this documentation.
### Crafting the Authorization Header
To authenticate a request, the sender must provide an `Authorization` or `ProxyAuthorization` header fulfilling the HMAC authentication scheme.
This header carries a set of parameters:
```bash
Authorization: Hmac keyId="secret-id-1",algorithm="hmac-sha256",headers="(request-target) (created) (expires) host x-example",signature="c29tZXNpZ25hdHVyZQ==",created="1584453022",expires="1584453032"
```
| Parameter | Description | Example |
|-------------|--------------------------------|------------------------------------|
| `keyId` | Identifier of the key being used by the sender to build the signature | `keyId="secret-key-1"` |
| `algorithm` | Algorithm used to generate the signature.<br /> Supported values are `hmac-sha1`, `hmac-sha256`, `hmac-sha384` and `hmac-sha512`. | `algorithm="hmac-sha512"` |
| `headers` | List of headers to use in order to build the signature string.<br /> Each item **must** be lowercase. | `headers="host content-type"` |
| `signature` | Digital Signature of the request. See [computing the signature](#computing-the-signature). | `signature="c29tZXNpZ25hdHVyZQ=="` |
| `created` | Unix timestamp of the signature creation. | `created="1574453022"` |
| `expires` | Unix timestamp of the signature expiration. | `expires="1574453022"` |
!!! danger "Time sensitivity"
If the `created` timestamp is in the future or the `expires` timestamp is in the past, the middleware will refuse the request.
This behaviour makes using this middleware sensitive to clock skew between the client and the server.
Make sure that your client and your server have their clocks synchronized.
### Computing the Signature
The signature is the base64-encoded value of the result of an HMAC signature algorithm computed with a `signature string` and the sender's `secret key`.
For example:
```bash
signature=base64(HMAC(signatureString, secret))
```
### Crafting the Signature String
A signed HTTP request needs to be tolerant of some trivial alterations during transmission as it goes through gateways, proxies and other entities.
As a consequence, signing the whole request is not an option as a single header modification could result in a not valid signature.
To avoid this problem, this middleware builds the `signature string` from a subset of header values defined by the sender with the `headers` parameter of the authorization header.
To build the signature string, the client **must** take the values of each header specified by the `headers` parameter **in the order they appear**, then apply the following logic to each of them:
1. If the header is a special header, then evaluate its value according to [the special headers values section](#special-header-values)
2. If the header is not a special header, then append the lowercase header name followed with an ASCII colon `:`, an ASCII space \` \` and the header value.
If the header has multiple values then append those values separated by an ASCII comma `,` and an ASCII space \` \`
3. If value is not the last value then append an ASCII newline `\n`. The signature string MUST NOT include a trailing ASCII newline
!!! warning
All headers values are trimmed from their spaces."
#### Special Header Values
By design, all the information of an HTTP request is not available through headers. However, it makes sense to secure the request using them.
To allow this, the `headers` parameter accepts special header names that can be used.
| Value | Description | Signature String Example |
| --------------------- | ------------------------------------------------------------- |------------------------- |
| `(request-target)` | Obtained by concatenating the lowercase `:method`, an ASCII space, and the `:path` pseudo-headers ([as specified in HTTP/2](https://tools.ietf.org/html/rfc7540#section-8.1.2.3)). | `(request-target): get /api/V1/resource?query=foo` |
| `(created)` | Value of the authorization header `created` parameter. | `(created): 1584453022` |
| `(expires)` | Value of the authorization header `expires` parameter. | `(expires): 1584453082` |
Their evaluated value is obtained by appending the special header name with an ASCII colon `:` an ASCII space \` \` then the designated value.
```bash tab="Example"
(created): 1929494939
(request-target): get /foo/bar
```
#### Signature String Example
Here is an example with the authorization header parameters set:
- `headers="(request-target) (created) (expires) host x-example x-emptyheader cache-control"`
- `created="1584466921"`
- `expires="1584466931"`
```bash tab="Request"
GET /foo HTTP/1.1
Host: example.org
X-Example: Example header
with some whitespace.
X-EmptyHeader:
X-NotIncluded: always
Cache-Control: max-age=60
Cache-Control: must-revalidate
```
```bash tab="Expected Signature String"
(request-target): get /foo
(created): 1584466921
(expires): 1584466931
host: example.org
x-example: Example header with some whitespace.
x-emptyheader:
cache-control: max-age=60, must-revalidate
```
#### Enforced Headers
It is possible to configure the middleware to enforce a minimum set of headers to create the signature string.
This means that any request that does not have the enforced headers in its signature is systematically refused.
This option also configures the headers list returned when [initiating the authentication](#initiating-the-authentication).
It defaults to `(request-target) (created) (expires)`.
!!! danger "Always enforce (created) and (expires)"
The `created` and `expires` header parameters protect against replay attacks.
To make sure that their value is not modified during transport, it is **highly recommended** to always include those parameters values in the signature using the `(created)` and `(expired)` special headers value.
To do so, it is recommended to **always** configure the middleware to enforce `(created)` and `(expires)`.
### Initiating the Authentication
The authentication can be initiated by the proxy. A `401 Unauthorized` response is returned with a `WWW-Authenticate` header indicating to use the `Hmac` authentication scheme.
```bash
WWW-Authenticate: Hmac headers="(request-target) (created) (expires) host x-example"
```
This header indicates that the sender needs to provide an Authorization header that fulfills the `Hmac` authentication schemes.
It also indicates a list of headers that have to be included in the signature using the `headers` parameter.
!!! note "Enforced headers"
The list of headers carried in the `WWW-Authenticate` header is the list of [enforced headers](#enforced-headers) indicated in the middleware configuration.
## Validating Request Body Integrity
It is possible to make sure that the body of the incoming request has not been altered during transmission by including the [digest header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Digest) in the signature string.
This middleware, by default, validates the digest sum of the body, if there is one.
Only SHA-256 and SHA-512 checksums are supported for checksum computation.
!!! warning "Potential CPU and memory usage"
Validating the digest makes the middleware read the request body and computes a checksum for it.
As a consequence it can cause high memory and CPU usage on proxies.
To disable this feature and only perform authentication, set the `validateDigest` option to `false` in the middleware configuration.
{!traefik-for-business-applications.md!}

View File

@ -0,0 +1,233 @@
---
title: 'JWT Authentication'
description: 'Traefik Hub API Gateway - The JWT Authentication middleware verifies that a valid JWT token is provided in the Authorization header.'
---
!!! info "Traefik Hub Feature"
This middleware is available exclusively in [Traefik Hub](https://traefik.io/traefik-hub/). Learn more about [Traefik Hub's advanced features](https://doc.traefik.io/traefik-hub/api-gateway/intro).
The JWT middleware verifies that a valid JWT token is provided in the `Authorization` header (`Authorization: Bearer <JWT>`).
If the token can't be passed as an `Authorization` header, it can be given as form data or as a query parameter.
See the `tokenKey` option for more information.
With no specific configuration, a JWT middleware only validates the signature of a JWT and checks the `nbf`, `exp` and `iat` standard claims (if they are present).
Custom claim validation can be configured with [Custom Claims Validation](#claims).
---
## Configuration Example
```yaml tab="Middleware JWT"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-jwt
spec:
plugin:
jwt:
signingSecret: my-secret
forwardHeaders:
Group: grp
Expires-At: exp
claims: Equals(`grp`, `admin`)
```
## Configuration Options
| Field | Description | Default | Required |
|:----------------|:------------------------------------------------|:--------|:---------|
| `signingSecret` | Defines the secret used for signing the JWT certificates. <br /> It is then used by the middleware to verify incoming requests. <br /> At least one of `signingSecret`, `publicKey`, `jwksFile` or `jwksUrl` options must be set. (More information [here](#signingsecret)) | "" | No |
| `signingSecretBase64Encoded` | Defines whether the `signingSecret` is base64-encoded. <br /> If set to `true`, the `signingSecret` is base64-decoded before being used. | false | No |
| `publicKey` | Defines the public key used to verify secret signature in incoming requests. <br /> In that case, users should sign their token using a private key corresponding to the configured public key. <br /> At least one of `signingSecret`, `publicKey`, `jwksFile` or `jwksUrl` options must be set. | "" | No |
| `jwksFile` | Defines a set of [JWK](https://tools.ietf.org/html/rfc7517) to be used to verify the signature of JWTs. <br /> The option can either be a path to a file mounted on the API Gateway or directly the content of a JWK set file. <br /> At least one of `signingSecret`, `publicKey`, `jwksFile` or `jwksUrl` options must be set. (More information [here](#jwksfile)) | "" | No |
| `jwksUrl` | Defines the URL of the host serving a [JWK](https://tools.ietf.org/html/rfc7517) set. <br />The keys are cached if the HTTP Cache Control allows for caching. <br /> At least one of `signingSecret`, `publicKey`, `jwksFile` or `jwksUrl` options must be set.<br />(More information [here](#jwksurl)) | "" | No |
| `forwardAuthorization` | Defines whether the authorization header will be forwarded or stripped from a request after it has been approved by the middleware. | false | No |
| `tokenKey` | Defines the name of the query and form data parameter used for passing the JWT, for applications that can't pass it in the `Authorization` header. <br /> The middleware always looks in the `Authorization` header first, even with this option enabled. <br /> This option should only be enabled if the JWT cannot be passed as an Authorization header, as it is not recommended by the [RFC](https://www.rfc-editor.org/rfc/rfc6750#section-2). | "" | No |
| `claims` | Defines the claims to validate in order to authorize the request. <br /> The `claims` option can only be used with JWT-formatted token. (More information [here](#claims)) | "" | No |
| `usernameClaim` | Defines the claim that will be evaluated to populate the `clientusername` in the access logs. <br /> The `usernameClaim` option can only be used with JWT-formatted token.| "" | No |
| `forwardHeaders` | Defines the HTTP headers to add to requests and populates them with values extracted from the access token claims returned by the authorization server. <br /> Claims to be forwarded that are not found in the JWT result in empty headers. <br /> The `forwardHeaders` option can only be used with JWT-formatted token. | [] | No |
| `clientConfig.tls.ca` | PEM-encoded certificate bundle or a URN referencing a secret containing the certificate bundle used to establish a TLS connection with the authorization server (More information [here](#clientconfig)) | "" | No |
| `clientConfig.tls.cert` | PEM-encoded certificate or a URN referencing a secret containing the certificate used to establish a TLS connection with the Vault server (More information [here](#clientconfig)) | "" | No |
| `clientConfig.tls.key` | PEM-encoded key or a URN referencing a secret containing the key used to establish a TLS connection with the Vault server. (More information [here](#clientconfig)) | "" | No |
| `clientConfig.tls.insecureSkipVerify` | Disables TLS certificate verification when communicating with the authorization server. <br /> Useful for testing purposes but strongly discouraged for production. (More information [here](#clientconfig)) | "" | No |
| `clientConfig.timeoutSeconds` | Defines the time before giving up requests to the authorization server. | 5 | No |
| `clientConfig.maxRetries` | Defines the number of retries for requests to authorization server that fail. | 3 | No |
### claims
#### Syntax
The following functions are supported in `claims`:
| Function | Description | Example |
|-------------------|--------------------|-----------------|
| Equals | Validates the equality of the value in `key` with `value`. | Equals(\`grp\`, \`admin\`) |
| Prefix | Validates the value in `key` has the prefix of `value`. | Prefix(\`referrer\`, \`http://example.com\`) |
| Contains (string) | Validates the value in `key` contains `value`. | Contains(\`referrer\`, \`/foo/\`) |
| Contains (array) | Validates the `key` array contains the `value`. | Contains(\`areas\`, \`home\`) |
| SplitContains | Validates the value in `key` contains the `value` once split by the separator. | SplitContains(\`scope\`, \` \`, \`writer\`) |
| OneOf | Validates the `key` array contains one of the `values`. | OneOf(\`areas\`, \`office\`, \`lab\`) |
All functions can be joined by boolean operands. The supported operands are:
| Operand | Description | Example |
|---------|--------------------|-----------------|
| && | Compares two functions and returns true only if both evaluate to true. | Equals(\`grp\`, \`admin\`) && Equals(\`active\`, \`true\`) |
| \|\| | Compares two functions and returns true if either evaluate to true. | Equals(\`grp\`, \`admin\`) \|\| Equals(\`active\`, \`true\`) |
| ! | Returns false if the function is true, otherwise returns true. | !Equals(\`grp\`, \`testers\`) |
All examples will return true for the following data structure:
```json tab="JSON"
{
"active": true,
"grp": "admin",
"scope": "reader writer deploy",
"referrer": "http://example.com/foo/bar",
"areas": [
"office",
"home"
]
}
```
#### Nested Claims
Nested claims are supported by using a `.` between keys. For example:
```bash tab="Key"
user.name
```
```json tab="Claims"
{
"active": true,
"grp": "admin",
"scope": "reader writer deploy",
"referrer": "http://example.com/foo/bar",
"areas": [
"office",
"home"
],
"user" {
"name": "John Snow",
"status": "undead"
}
}
```
```bash tab="Result"
John Snow
```
!!! note "Handling keys that contain a '.'"
If the `key` contains a dot, the dot can be escaped using `\.`
!!! note "Handling a key that contains a '\'"
If the `key` contains a `\`, it needs to be doubled `\\`.
### clientConfig
Defines the configuration used to connect the API Gateway to a Third Party Software such as an Identity Provider.
#### `clientConfig.tls`
##### Storing secret values in Kubernetes secrets
When configuring the `tls.ca`, `tls.cert`, `tls.key`, it is possible to reference Kubernetes secrets defined in the same namespace as the Middleware.
The reference to a Kubernetes secret takes the form of a URN:
```text
urn:k8s:secret:[name]:[valueKey]
```
```yaml tab="Middleware JWT"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-jwt
spec:
plugin:
jwt:
clientConfig:
tls:
ca: "urn:k8s:secret:tls:ca"
cert: "urn:k8s:secret:tls:cert"
key: "urn:k8s:secret:tls:key"
insecureSkipVerify: true
```
```yaml tab="Kubernetes TLS Secret"
apiVersion: v1
kind: Secret
metadata:
name: tls
stringData:
ca: |-
-----BEGIN CERTIFICATE-----
MIIB9TCCAWACAQAwgbgxGTAXBgNVBAoMEFF1b1ZhZGlzIExpbWl0ZWQxHDAaBgNV
BAsME0RvY3VtZW50IERlcGFydG1lbnQxOTA3BgNVBAMMMFdoeSBhcmUgeW91IGRl
Y29kaW5nIG1lPyAgVGhpcyBpcyBvbmx5IGEgdGVzdCEhITERMA8GA1UEBwwISGFt
aWx0b24xETAPBgNVBAgMCFBlbWJyb2tlMQswCQYDVQQGEwJCTTEPMA0GCSqGSIb3
DQEJARYAMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJ9WRanG/fUvcfKiGl
EL4aRLjGt537mZ28UU9/3eiJeJznNSOuNLnF+hmabAu7H0LT4K7EdqfF+XUZW/2j
RKRYcvOUDGF9A7OjW7UfKk1In3+6QDCi7X34RE161jqoaJjrm/T18TOKcgkkhRzE
apQnIDm0Ea/HVzX/PiSOGuertwIDAQABMAsGCSqGSIb3DQEBBQOBgQBzMJdAV4QP
Awel8LzGx5uMOshezF/KfP67wJ93UW+N7zXY6AwPgoLj4Kjw+WtU684JL8Dtr9FX
ozakE+8p06BpxegR4BR3FMHf6p+0jQxUEAkAyb/mVgm66TyghDGC6/YkiKoZptXQ
98TwDIK/39WEB/V607As+KoYazQG8drorw==
-----END CERTIFICATE-----
cert: |-
-----BEGIN CERTIFICATE-----
MIIB9TCCAWACAQAwgbgxGTAXBgNVBAoMEFF1b1ZhZGlzIExpbWl0ZWQxHDAaBgNV
BAsME0RvY3VtZW50IERlcGFydG1lbnQxOTA3BgNVBAMMMFdoeSBhcmUgeW91IGRl
Y29kaW5nIG1lPyAgVGhpcyBpcyBvbmx5IGEgdGVzdCEhITERMA8GA1UEBwwISGFt
aWx0b24xETAPBgNVBAgMCFBlbWJyb2tlMQswCQYDVQQGEwJCTTEPMA0GCSqGSIb3
DQEJARYAMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJ9WRanG/fUvcfKiGl
EL4aRLjGt537mZ28UU9/3eiJeJznNSOuNLnF+hmabAu7H0LT4K7EdqfF+XUZW/2j
RKRYcvOUDGF9A7OjW7UfKk1In3+6QDCi7X34RE161jqoaJjrm/T18TOKcgkkhRzE
apQnIDm0Ea/HVzX/PiSOGuertwIDAQABMAsGCSqGSIb3DQEBBQOBgQBzMJdAV4QP
Awel8LzGx5uMOshezF/KfP67wJ93UW+N7zXY6AwPgoLj4Kjw+WtU684JL8Dtr9FX
ozakE+8p06BpxegR4BR3FMHf6p+0jQxUEAkAyb/mVgm66TyghDGC6/YkiKoZptXQ
98TwDIK/39WEB/V607As+KoYazQG8drorw==
-----END CERTIFICATE-----
key: |-
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIC8CsJ/B115S+JtR1/l3ZQwKA3XdXt9zLqusF1VXc/KloAoGCCqGSM49
AwEHoUQDQgAEpwUmRIZHFt8CdDHYm1ikScCScd2q6QVYXxJu+G3fQZ78ScGtN7fu
KXMnQqVjXVRAr8qUY8yipVKuMCepnPXScQ==
-----END EC PRIVATE KEY-----
```
### jwksFile
#### JWT Header Key ID
If the JWT header contains a `kid` header, the middleware expects to find a JWK.
If a JWK cannot be found, it returns a `401 Unauthorized` error.
### jwksUrl
#### JWT Header Key ID
If the JWT header contains a `kid` header, the middleware expects to find a JWK.
If a JWK cannot be found, it returns a `401 Unauthorized` error.
#### JWT Issuer Claim
If `jwksUrl` is set to a path and the `iss` property is missing in the JWT it's trying to verify, the middleware returns a `401 Unauthorized` error.
### signingSecret
#### Storing secret values in Kubernetes secrets
When configuring the `signingSecret`, it is possible to reference a Kubernetes secret defined in the same namespace as the Middleware.
The reference to a Kubernetes secret takes the form of a URN:
```text
urn:k8s:secret:[name]:[valueKey]
```
{!traefik-for-business-applications.md!}

View File

@ -0,0 +1,105 @@
---
title: 'LDAP Authentication'
description: 'Traefik Hub API Gateway - The LDAP Authentication middleware secures your applications by delegating the authentication to an external LDAP server.'
---
!!! info "Traefik Hub Feature"
This middleware is available exclusively in [Traefik Hub](https://traefik.io/traefik-hub/). Learn more about [Traefik Hub's advanced features](https://doc.traefik.io/traefik-hub/api-gateway/intro).
The LDAP Authentication middleware secures your applications by delegating the authentication to an external LDAP server.
The LDAP middleware will look for user credentials in the `Authorization` header of each request. Credentials must be encoded with the following format: `base64(username:password)`.
---
## Configuration Examples
```yaml tab="Basic usage"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-ldap-auth
namespace: apps
spec:
plugin:
ldap:
url: ldap://ldap.example.org:636
baseDN: dc=example,dc=org
```
```yaml tab="Basic usage with bind need"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-ldap-auth
namespace: apps
spec:
plugin:
ldap:
url: ldap://ldap.example.org:636
baseDN: dc=example,dc=org
bindDN: cn=binding_user,dc=example,dc=org
bindPassword: "urn:k8s:secret:my-secret:bindpassword"
```
```yaml tab="Enabling search, bind & WWW-Authenticate header"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-ldap-auth
namespace: apps
spec:
plugin:
ldap:
url: ldap://ldap.example.org:636
baseDN: dc=example,dc=org
searchFilter: (&(objectClass=inetOrgPerson)(gidNumber=500)(uid=%s))
forwardUsername: true
forwardUsernameHeader: Custom-Username-Header-Name
wwwAuthenticateHeader: true
wwwAuthenticateHeaderRealm: traefikee
```
## Configuration Options
| Field | Description | Default | Required |
|:------|:------------|:--------|:---------|
| `url` | LDAP server URL. Either the `ldaps` or `ldap` protocol and end with a port (ex: `ldaps://ldap.example.org:636`). | "" | Yes |
| `startTLS` | Enable [`StartTLS`](https://tools.ietf.org/html/rfc4511#section-4.14) request when initializing the connection with the LDAP server. | false | No |
| `certificateAuthority` | PEM-encoded certificate to use to establish a connection with the LDAP server if the connection uses TLS but that the certificate was signed by a custom Certificate Authority. | "" | No |
| `insecureSkipVerify` | Allow proceeding and operating even for server TLS connections otherwise considered insecure. | false | No |
| `bindDN` | Domain name to bind to in order to authenticate to the LDAP server when running on search mode.<br /> Leaving this empty with search mode means binds are anonymous, which is rarely expected behavior.<br /> Not used when running in [bind mode](#bind-mode-vs-search-mode). | "" | No |
| `bindPassword` | Password for the `bindDN` used in search mode to authenticate with the LDAP server. More information [here](#bindpassword) | "" | No |
| `connPool` | Pool of connections to the LDAP server (to minimize the impact on the performance). | None | No |
| `connPool.size` | Number of connections managed by the pool can be customized with the `size` property. | 10 | No |
| `connPool.burst` | Ephemeral connections that are opened when the pool is already full. Once the number of connection exceeds `size` + `burst`, a `Too Many Connections` error is returned. | 5 | No |
| `connPool.ttl` | Pooled connections are still meant to be short-lived, so they are closed after roughly one minute by default. This behavior can be modified with the `ttl` property. | 60s | No |
| `baseDN` | Base domain name that should be used for bind and search queries. | "" | Yes |
| `attribute` | The attribute used to bind a user. Bind queries use this pattern: `<attr>=<username>,<baseDN>`, where the username is extracted from the request header. | cn | Yes |
| `forwardUsername` | Forward the username in a specific header, defined using the `forwardUsernameHeader` option. | "" | No |
| `forwardUsernameHeader` | Name of the header to put the username in when forwarding it. This is not used if the `forwardUsername` option is set to `false`. | Username | Yes |
| `forwardAuthorization` | Enable to forward the authorization header from the request after it has been approved by the middleware. | false | Yes |
| `searchFilter` | If not empty, the middleware will run in [search mode](#bind-mode-vs-search-mode), filtering search results with the given query.<br />Filter queries can use the `%s` placeholder that is replaced by the username provided in the `Authorization` header of the request (for example: `(&(objectClass=inetOrgPerson)(gidNumber=500)(uid=%s))`). | "" | No |
| `wwwAuthenticateHeader` | Allow setting a `WWW-Authenticate` header in the `401 Unauthorized` response. See [the WWW-Authenticate header documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate) for more information.<br /> The `realm` directive of the `WWW-Authenticate` header can be customized with the `wwwAuthenticateHeaderRealm` option. | false | No |
| `wwwAuthenticateHeaderRealm` | Realm name to set in the `WWW-Authenticate` header. This option is ineffective unless the `wwwAuthenticateHeader` option is set to `true`. | "" | No |
### bindPassword
When setting the `bindPassword`, you can reference a Kubernetes secret from the same namespace as the Middleware using the following URN format:
```text
urn:k8s:secret:[secretName]:[key]
```
## Bind Mode vs Search Mode
If no filter is specified in its configuration, the middleware runs in the default bind mode,
meaning it tries to make a bind request to the LDAP server with the credentials provided in the request headers.
If the bind succeeds, the middleware forwards the request, otherwise it returns a `401 Unauthorized` status code.
If a filter query is specified in the middleware configuration, and the Authentication Source referenced has a `bindDN`
and a `bindPassword`, then the middleware runs in search mode. In this mode, a search query with the given filter is
issued to the LDAP server before trying to bind. If result of this search returns only 1 record,
it tries to issue a bind request with this record, otherwise it aborts a `401 Unauthorized` status code.
{!traefik-for-business-applications.md!}

View File

@ -0,0 +1,255 @@
---
title: 'OAuth 2.0 Client Credentials Authentication'
description: 'Traefik Hub API Gateway - The OAuth 2.0 Client Credentials Authentication middleware secures your applications using the client credentials flow'
---
!!! info "Traefik Hub Feature"
This middleware is available exclusively in [Traefik Hub](https://traefik.io/traefik-hub/). Learn more about [Traefik Hub's advanced features](https://doc.traefik.io/traefik-hub/api-gateway/intro).
The OAuth 2.0 Client Credentials Authentication middleware allows Traefik Hub to secure routes using the OAuth 2.0 Client Credentials flow as described in the [RFC 6749](https://www.rfc-editor.org/rfc/rfc6749.html#section-4.4).
Access tokens can be cached using an external KV store.
The OAuth Client Credentials Authentication middleware allows using Redis (or Sentinel) as persistent KV store to authorization access tokens
while they are valid. This reduces latency and the number of calls made to the authorization server.
---
## Configuration Example
```yaml tab="Middleware OAuth Client Credentials"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-client-creds
spec:
plugin:
oAuthClientCredentials:
url: https://tenant.auth0.com/oauth/token
clientID: urn:k8s:my-secret:my-secret:clientID
clientSecret: urn:k8s:my-secret:my-secret:clientSecret
audience: https://api.example.com
forwardHeaders:
Group: grp
Expires-At: exp
claims: Equals(`grp`, `admin`)
```
```yaml tab="Kubernetes Secret"
apiVersion: v1
kind: Secret
type: Opaque
metadata:
name: my-secret
stringData:
clientID: my-oauth-client-name
clientSecret: mypasswd
```
## Configuration Options
| Field | Description | Default | Required |
|:------|:--------------------------------------------------------------------------------------------|:--------|:---------|
| `audience` | Defines the audience configured in your authorization server. <br /> The audience value is the base address of the resource being accessed, for example: https://api.example.com. | "" | Yes |
| `claims` | Defines the claims to validate in order to authorize the request. <br /> The `claims` option can only be used with JWT-formatted token. (More information [here](#claims)) | "" | No |
| `clientConfig.tls.ca` | PEM-encoded certificate bundle or a URN referencing a secret containing the certificate bundle used to establish a TLS connection with the authorization server (More information [here](#clientconfig)) | "" | No |
| `clientConfig.tls.cert` | PEM-encoded certificate or a URN referencing a secret containing the certificate used to establish a TLS connection with the Vault server (More information [here](#clientconfig)) | "" | No |
| `clientConfig.tls.key` | PEM-encoded key or a URN referencing a secret containing the key used to establish a TLS connection with the Vault server. (More information [here](#clientconfig)) | "" | No |
| `clientConfig.tls.insecureSkipVerify` | Disables TLS certificate verification when communicating with the authorization server. <br /> Useful for testing purposes but strongly discouraged for production. (More information [here](#clientconfig)) | "" | No |
| `clientConfig.timeoutSeconds` | Defines the time before giving up requests to the authorization server. | 5 | No |
| `clientConfig.maxRetries` | Defines the number of retries for requests to authorization server that fail. | 3 | No |
| `clientID` | Defines the unique client identifier for an account on the OpenID Connect provider, must be set when the `clientSecret` option is set.<br />More information [here](#storing-secret-values-in-kubernetes-secrets). | "" | Yes |
| `clientSecret` | Defines the unique client secret for an account on the OpenID Connect provider, must be set when the `clientID` option is set.<br />More information [here](#storing-secret-values-in-kubernetes-secrets). | "" | Yes |
| `forwardHeaders` | Defines the HTTP headers to add to requests and populates them with values extracted from the access token claims returned by the authorization server. <br /> Claims to be forwarded that are not found in the JWT result in empty headers. <br /> The `forwardHeaders` option can only be used with JWT-formatted token. | [] | No |
| `store.keyPrefix` | Defines the prefix of the key for the entries that store the sessions. | "" | No |
| `store.redis.endpoints` | Endpoints of the Redis instances to connect to (example: `redis.traefik-hub.svc.cluster.local:6379`) | "" | Yes |
| `store.redis.username` | The username Traefik Hub will use to connect to Redis | "" | No |
| `store.redis.password` | The password Traefik Hub will use to connect to Redis | "" | No |
| `store.redis.database` | The database Traefik Hub will use to sore information (default: `0`) | "" | No |
| `store.redis.cluster` | Enable Redis Cluster | "" | No |
| `store.redis.tls.caBundle` | Custom CA bundle | "" | No |
| `store.redis.tls.cert` | TLS certificate | "" | No |
| `store.redis.tls.key` | TLS | "" | No |
| `store.redis.tls.insecureSkipVerify` | Allow skipping the TLS verification | "" | No |
| `store.redis.sentinel.masterSet` | Name of the set of main nodes to use for main selection. Required when using Sentinel. | "" | No |
| `store.redis.sentinel.username` | Username to use for sentinel authentication (can be different from `username`) | "" | No |
| `store.redis.sentinel.password` | Password to use for sentinel authentication (can be different from `password`) | "" | No |
| `url` | Defines the authorization server URL (for example: `https://tenant.auth0.com/oauth/token`). | "" | Yes |
| `usernameClaim` | Defines the claim that will be evaluated to populate the `clientusername` in the access logs. <br /> The `usernameClaim` option can only be used with JWT-formatted token.| "" | No |
### Storing secret values in Kubernetes secrets
It is possible to reference Kubernetes secrets defined in the same namespace as the Middleware.
The reference to a Kubernetes secret takes the form of a URN:
```text
urn:k8s:secret:[name]:[valueKey]
```
### claims
#### Syntax
The following functions are supported in `claims`:
| Function | Description | Example |
|-------------------|--------------------|-----------------|
| Equals | Validates the equality of the value in `key` with `value`. | Equals(\`grp\`, \`admin\`) |
| Prefix | Validates the value in `key` has the prefix of `value`. | Prefix(\`referrer\`, \`http://example.com\`) |
| Contains (string) | Validates the value in `key` contains `value`. | Contains(\`referrer\`, \`/foo/\`) |
| Contains (array) | Validates the `key` array contains the `value`. | Contains(\`areas\`, \`home\`) |
| SplitContains | Validates the value in `key` contains the `value` once split by the separator. | SplitContains(\`scope\`, \` \`, \`writer\`) |
| OneOf | Validates the `key` array contains one of the `values`. | OneOf(\`areas\`, \`office\`, \`lab\`) |
All functions can be joined by boolean operands. The supported operands are:
| Operand | Description | Example |
|---------|--------------------|-----------------|
| && | Compares two functions and returns true only if both evaluate to true. | Equals(\`grp\`, \`admin\`) && Equals(\`active\`, \`true\`) |
| \|\| | Compares two functions and returns true if either evaluate to true. | Equals(\`grp\`, \`admin\`) \|\| Equals(\`active\`, \`true\`) |
| ! | Returns false if the function is true, otherwise returns true. | !Equals(\`grp\`, \`testers\`) |
All examples will return true for the following data structure:
```json tab="JSON"
{
"active": true,
"grp": "admin",
"scope": "reader writer deploy",
"referrer": "http://example.com/foo/bar",
"areas": [
"office",
"home"
]
}
```
#### Nested Claims
Nested claims are supported by using a `.` between keys. For example:
```bash tab="Key"
user.name
```
```json tab="Claims"
{
"active": true,
"grp": "admin",
"scope": "reader writer deploy",
"referrer": "http://example.com/foo/bar",
"areas": [
"office",
"home"
],
"user" {
"name": "John Snow",
"status": "undead"
}
}
```
```bash tab="Result"
John Snow
```
!!! note "Handling keys that contain a '.'"
If the `key` contains a dot, the dot can be escaped using `\.`
!!! note "Handling a key that contains a '\'"
If the `key` contains a `\`, it needs to be doubled `\\`.
### clientConfig
Defines the configuration used to connect the API Gateway to a Third Party Software such as an Identity Provider.
#### `clientConfig.tls`
##### Storing secret values in Kubernetes secrets
When configuring the `tls.ca`, `tls.cert`, `tls.key`, it is possible to reference Kubernetes secrets defined in the same namespace as the Middleware.
The reference to a Kubernetes secret takes the form of a URN:
```text
urn:k8s:secret:[name]:[valueKey]
```
```yaml tab="Middleware JWT"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-client-creds
spec:
plugin:
oAuthClientCredentials:
clientConfig:
tls:
ca: "urn:k8s:secret:tls:ca"
cert: "urn:k8s:secret:tls:cert"
key: "urn:k8s:secret:tls:key"
insecureSkipVerify: true
```
```yaml tab="Kubernetes TLS Secret"
apiVersion: v1
kind: Secret
metadata:
name: tls
stringData:
ca: |-
-----BEGIN CERTIFICATE-----
MIIB9TCCAWACAQAwgbgxGTAXBgNVBAoMEFF1b1ZhZGlzIExpbWl0ZWQxHDAaBgNV
BAsME0RvY3VtZW50IERlcGFydG1lbnQxOTA3BgNVBAMMMFdoeSBhcmUgeW91IGRl
Y29kaW5nIG1lPyAgVGhpcyBpcyBvbmx5IGEgdGVzdCEhITERMA8GA1UEBwwISGFt
aWx0b24xETAPBgNVBAgMCFBlbWJyb2tlMQswCQYDVQQGEwJCTTEPMA0GCSqGSIb3
DQEJARYAMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJ9WRanG/fUvcfKiGl
EL4aRLjGt537mZ28UU9/3eiJeJznNSOuNLnF+hmabAu7H0LT4K7EdqfF+XUZW/2j
RKRYcvOUDGF9A7OjW7UfKk1In3+6QDCi7X34RE161jqoaJjrm/T18TOKcgkkhRzE
apQnIDm0Ea/HVzX/PiSOGuertwIDAQABMAsGCSqGSIb3DQEBBQOBgQBzMJdAV4QP
Awel8LzGx5uMOshezF/KfP67wJ93UW+N7zXY6AwPgoLj4Kjw+WtU684JL8Dtr9FX
ozakE+8p06BpxegR4BR3FMHf6p+0jQxUEAkAyb/mVgm66TyghDGC6/YkiKoZptXQ
98TwDIK/39WEB/V607As+KoYazQG8drorw==
-----END CERTIFICATE-----
cert: |-
-----BEGIN CERTIFICATE-----
MIIB9TCCAWACAQAwgbgxGTAXBgNVBAoMEFF1b1ZhZGlzIExpbWl0ZWQxHDAaBgNV
BAsME0RvY3VtZW50IERlcGFydG1lbnQxOTA3BgNVBAMMMFdoeSBhcmUgeW91IGRl
Y29kaW5nIG1lPyAgVGhpcyBpcyBvbmx5IGEgdGVzdCEhITERMA8GA1UEBwwISGFt
aWx0b24xETAPBgNVBAgMCFBlbWJyb2tlMQswCQYDVQQGEwJCTTEPMA0GCSqGSIb3
DQEJARYAMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJ9WRanG/fUvcfKiGl
EL4aRLjGt537mZ28UU9/3eiJeJznNSOuNLnF+hmabAu7H0LT4K7EdqfF+XUZW/2j
RKRYcvOUDGF9A7OjW7UfKk1In3+6QDCi7X34RE161jqoaJjrm/T18TOKcgkkhRzE
apQnIDm0Ea/HVzX/PiSOGuertwIDAQABMAsGCSqGSIb3DQEBBQOBgQBzMJdAV4QP
Awel8LzGx5uMOshezF/KfP67wJ93UW+N7zXY6AwPgoLj4Kjw+WtU684JL8Dtr9FX
ozakE+8p06BpxegR4BR3FMHf6p+0jQxUEAkAyb/mVgm66TyghDGC6/YkiKoZptXQ
98TwDIK/39WEB/V607As+KoYazQG8drorw==
-----END CERTIFICATE-----
key: |-
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIC8CsJ/B115S+JtR1/l3ZQwKA3XdXt9zLqusF1VXc/KloAoGCCqGSM49
AwEHoUQDQgAEpwUmRIZHFt8CdDHYm1ikScCScd2q6QVYXxJu+G3fQZ78ScGtN7fu
KXMnQqVjXVRAr8qUY8yipVKuMCepnPXScQ==
-----END EC PRIVATE KEY-----
```
### store.redis
Connection parameters to your [Redis](https://redis.io/ "Link to website of Redis") server are attached to your Middleware deployment.
The following Redis modes are supported:
- Single instance mode
- [Redis Cluster](https://redis.io/docs/management/scaling "Link to official Redis documentation about Redis Cluster mode")
- [Redis Sentinel](https://redis.io/docs/management/sentinel "Link to official Redis documentation about Redis Sentinel mode")
!!! info
If you use Redis in single instance mode or Redis Sentinel, you can configure the `database` field.
This value won't be taken into account if you use Redis Cluster (only database `0` is available).
In this case, a warning is displayed, and the value is ignored.
For more information about Redis, we recommend the [official Redis documentation](https://redis.io/docs/ "Link to official Redis documentation").
{!traefik-for-business-applications.md!}

View File

@ -0,0 +1,209 @@
---
title: 'OAuth 2.0 Token Introspection Authentication'
description: 'Traefik Hub API Gateway - OAuth 2.0 Token Introspection allows to retrieve metadata about an access token from an OAuth 2.0 server.'
---
!!! info "Traefik Hub Feature"
This middleware is available exclusively in [Traefik Hub](https://traefik.io/traefik-hub/). Learn more about [Traefik Hub's advanced features](https://doc.traefik.io/traefik-hub/api-gateway/intro).
OAuth 2.0 Token Introspection allows Traefik Hub to retrieve metadata about an access token from an OAuth 2.0 server with the Token Introspection extension.
The metadata can be used to restrict the access to applications. For more information please refer to the [RFC](https://tools.ietf.org/html/rfc7662).
---
## Configuration Example
```yaml tab="Middleware OAuth Token Introspection"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-oauth-intro
spec:
plugin:
oAuthIntrospection:
tokenSource:
header: Authorization
headerAuthScheme: Bearer
clientConfig:
url: "https://YOUR-KEYCLOAK-ADDRESS/realms/YOUR-REALM/protocol/openid-connect/token/introspect"
headers:
Authorization: Basic ZXhhbXBsZTpleGFtcGxl # echo -n "$CLIENT_ID:$CLIENT_SECRET" | base64
tokenTypeHint: access_token
forwardHeaders:
Group: grp
Expires-At: exp
claims: Equals(`grp`, `admin`)
```
## Configuration Options
| Field | Description | Default | Required |
|:------|:------------|:--------|:---------|
| `claims` | Defines the claims to validate in order to authorize the request. <br /> The `claims` option can only be used with JWT-formatted token. (More information [here](#claims)) | "" | No |
| `clientConfig.url` | Defines the introspection endpoint URL. It must include the scheme and path. | "" | Yes |
| `clientConfig.headers` | Defines the headers to send in every introspection request. Values can be plain strings or a valid [Go template](https://pkg.go.dev/text/template). <br /> Currently, a variable of type [`Request`](https://pkg.go.dev/net/http#Request) corresponding to the request being introspected is accessible in templates. | "" | No |
| `clientConfig.tokenTypeHint` | Defines the type of token being introspected, sent as a hint to the introspection server. <br /> Please refer to the [official documentation](https://tools.ietf.org/html/rfc7662) for more details. | "" | No |
| `clientConfig.tls.ca` | PEM-encoded certificate bundle or a URN referencing a secret containing the certificate bundle used to establish a TLS connection with the authorization server (More information [here](#clientconfig)) | "" | No |
| `clientConfig.tls.cert` | PEM-encoded certificate or a URN referencing a secret containing the certificate used to establish a TLS connection with the Vault server (More information [here](#clientconfig)) | "" | No |
| `clientConfig.tls.key` | PEM-encoded key or a URN referencing a secret containing the key used to establish a TLS connection with the Vault server. (More information [here](#clientconfig)) | "" | No |
| `clientConfig.tls.insecureSkipVerify` | Disables TLS certificate verification when communicating with the authorization server. <br /> Useful for testing purposes but strongly discouraged for production. (More information [here](#clientconfig)) | "" | No |
| `clientConfig.timeoutSeconds` | Defines the time before giving up requests to the authorization server. | 5 | No |
| `clientConfig.maxRetries` | Defines the number of retries for requests to authorization server that fail. | 3 | No |
| `forwardAuthorization` | Defines whether the authorization header will be forwarded or stripped from a request after it has been approved by the middleware. | false | No |
| `forwardHeaders` | Defines the HTTP headers to add to requests and populates them with values extracted from the access token claims returned by the authorization server. <br /> Claims to be forwarded that are not found in the JWT result in empty headers. <br /> The `forwardHeaders` option can only be used with JWT-formatted token. | [] | No |
| `tokenSource.header` | Defines the header name containing the secret sent by the client.<br />At least one `tokenSource`option must be set.| "" | No |
| `tokenSource.headerAuthScheme` | Defines the scheme when using `Authorization` as header name. <br /> Check out the `Authorization` header [documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization#syntax).<br />At least one `tokenSource`option must be set. | "" | No |
| `tokenSource.query` | Defines the query parameter name containing the secret sent by the client.<br />At least one `tokenSource`option must be set.| "" | No |
| `tokenSource.cookie` | Defines the cookie name containing the secret sent by the client.<br />At least one `tokenSource`option must be set.| "" | No |
| `usernameClaim` | Defines the claim that will be evaluated to populate the `clientusername` in the access logs. <br /> The `usernameClaim` option can only be used with JWT-formatted token.| "" | No |
### claims
#### Syntax
The following functions are supported in `claims`:
| Function | Description | Example |
|-------------------|--------------------|-----------------|
| Equals | Validates the equality of the value in `key` with `value`. | Equals(\`grp\`, \`admin\`) |
| Prefix | Validates the value in `key` has the prefix of `value`. | Prefix(\`referrer\`, \`http://example.com\`) |
| Contains (string) | Validates the value in `key` contains `value`. | Contains(\`referrer\`, \`/foo/\`) |
| Contains (array) | Validates the `key` array contains the `value`. | Contains(\`areas\`, \`home\`) |
| SplitContains | Validates the value in `key` contains the `value` once split by the separator. | SplitContains(\`scope\`, \` \`, \`writer\`) |
| OneOf | Validates the `key` array contains one of the `values`. | OneOf(\`areas\`, \`office\`, \`lab\`) |
All functions can be joined by boolean operands. The supported operands are:
| Operand | Description | Example |
|---------|--------------------|-----------------|
| && | Compares two functions and returns true only if both evaluate to true. | Equals(\`grp\`, \`admin\`) && Equals(\`active\`, \`true\`) |
| \|\| | Compares two functions and returns true if either evaluate to true. | Equals(\`grp\`, \`admin\`) \|\| Equals(\`active\`, \`true\`) |
| ! | Returns false if the function is true, otherwise returns true. | !Equals(\`grp\`, \`testers\`) |
All examples will return true for the following data structure:
```json tab="JSON"
{
"active": true,
"grp": "admin",
"scope": "reader writer deploy",
"referrer": "http://example.com/foo/bar",
"areas": [
"office",
"home"
]
}
```
#### Nested Claims
Nested claims are supported by using a `.` between keys. For example:
```bash tab="Key"
user.name
```
```json tab="Claims"
{
"active": true,
"grp": "admin",
"scope": "reader writer deploy",
"referrer": "http://example.com/foo/bar",
"areas": [
"office",
"home"
],
"user" {
"name": "John Snow",
"status": "undead"
}
}
```
```bash tab="Result"
John Snow
```
!!! note "Handling keys that contain a '.'"
If the `key` contains a dot, the dot can be escaped using `\.`
!!! note "Handling a key that contains a '\'"
If the `key` contains a `\`, it needs to be doubled `\\`.
### clientConfig
Defines the configuration used to connect the API Gateway to a Third Party Software such as an Identity Provider.
#### `clientConfig.tls`
##### Storing secret values in Kubernetes secrets
When configuring the `tls.ca`, `tls.cert`, `tls.key`, it is possible to reference Kubernetes secrets defined in the same namespace as the Middleware.
The reference to a Kubernetes secret takes the form of a URN:
```text
urn:k8s:secret:[name]:[valueKey]
```
```yaml tab="Middleware JWT"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-oauth-intro
spec:
plugin:
oAuthIntrospection:
clientConfig:
tls:
ca: "urn:k8s:secret:tls:ca"
cert: "urn:k8s:secret:tls:cert"
key: "urn:k8s:secret:tls:key"
insecureSkipVerify: true
```
```yaml tab="Kubernetes TLS Secret"
apiVersion: v1
kind: Secret
metadata:
name: tls
stringData:
ca: |-
-----BEGIN CERTIFICATE-----
MIIB9TCCAWACAQAwgbgxGTAXBgNVBAoMEFF1b1ZhZGlzIExpbWl0ZWQxHDAaBgNV
BAsME0RvY3VtZW50IERlcGFydG1lbnQxOTA3BgNVBAMMMFdoeSBhcmUgeW91IGRl
Y29kaW5nIG1lPyAgVGhpcyBpcyBvbmx5IGEgdGVzdCEhITERMA8GA1UEBwwISGFt
aWx0b24xETAPBgNVBAgMCFBlbWJyb2tlMQswCQYDVQQGEwJCTTEPMA0GCSqGSIb3
DQEJARYAMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJ9WRanG/fUvcfKiGl
EL4aRLjGt537mZ28UU9/3eiJeJznNSOuNLnF+hmabAu7H0LT4K7EdqfF+XUZW/2j
RKRYcvOUDGF9A7OjW7UfKk1In3+6QDCi7X34RE161jqoaJjrm/T18TOKcgkkhRzE
apQnIDm0Ea/HVzX/PiSOGuertwIDAQABMAsGCSqGSIb3DQEBBQOBgQBzMJdAV4QP
Awel8LzGx5uMOshezF/KfP67wJ93UW+N7zXY6AwPgoLj4Kjw+WtU684JL8Dtr9FX
ozakE+8p06BpxegR4BR3FMHf6p+0jQxUEAkAyb/mVgm66TyghDGC6/YkiKoZptXQ
98TwDIK/39WEB/V607As+KoYazQG8drorw==
-----END CERTIFICATE-----
cert: |-
-----BEGIN CERTIFICATE-----
MIIB9TCCAWACAQAwgbgxGTAXBgNVBAoMEFF1b1ZhZGlzIExpbWl0ZWQxHDAaBgNV
BAsME0RvY3VtZW50IERlcGFydG1lbnQxOTA3BgNVBAMMMFdoeSBhcmUgeW91IGRl
Y29kaW5nIG1lPyAgVGhpcyBpcyBvbmx5IGEgdGVzdCEhITERMA8GA1UEBwwISGFt
aWx0b24xETAPBgNVBAgMCFBlbWJyb2tlMQswCQYDVQQGEwJCTTEPMA0GCSqGSIb3
DQEJARYAMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJ9WRanG/fUvcfKiGl
EL4aRLjGt537mZ28UU9/3eiJeJznNSOuNLnF+hmabAu7H0LT4K7EdqfF+XUZW/2j
RKRYcvOUDGF9A7OjW7UfKk1In3+6QDCi7X34RE161jqoaJjrm/T18TOKcgkkhRzE
apQnIDm0Ea/HVzX/PiSOGuertwIDAQABMAsGCSqGSIb3DQEBBQOBgQBzMJdAV4QP
Awel8LzGx5uMOshezF/KfP67wJ93UW+N7zXY6AwPgoLj4Kjw+WtU684JL8Dtr9FX
ozakE+8p06BpxegR4BR3FMHf6p+0jQxUEAkAyb/mVgm66TyghDGC6/YkiKoZptXQ
98TwDIK/39WEB/V607As+KoYazQG8drorw==
-----END CERTIFICATE-----
key: |-
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIC8CsJ/B115S+JtR1/l3ZQwKA3XdXt9zLqusF1VXc/KloAoGCCqGSM49
AwEHoUQDQgAEpwUmRIZHFt8CdDHYm1ikScCScd2q6QVYXxJu+G3fQZ78ScGtN7fu
KXMnQqVjXVRAr8qUY8yipVKuMCepnPXScQ==
-----END EC PRIVATE KEY-----
```
{!traefik-for-business-applications.md!}

View File

@ -0,0 +1,430 @@
---
title: 'OpenID Connect Authentication'
description: 'Traefik Hub API Gateway - The OIDC Authentication middleware secures your applications by delegating the authentication to an external provider.'
---
!!! info "Traefik Hub Feature"
This middleware is available exclusively in [Traefik Hub](https://traefik.io/traefik-hub/). Learn more about [Traefik Hub's advanced features](https://doc.traefik.io/traefik-hub/api-gateway/intro).
The OIDC Authentication middleware secures your applications by delegating the authentication to an external provider
---
## Configuration Example
```yaml tab="Middleware OIDC"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-oidc
namespace: whoami
spec:
plugin:
oidc:
issuer: "https://tenant.auth0.com/realms/myrealm"
redirectUrl: "/callback"
clientID: "urn:k8s:secret:my-secret:clientId"
clientSecret: "urn:k8s:secret:my-secret:clientSecret"
session:
name: customsessioncookiename
sliding: false
refresh: false
expiry: 10
sameSite: none
httpOnly: false
secure: true
stateCookie:
name: customstatecookiename
maxAge: 10
sameSite: none
httpOnly: true
secure: true
forwardHeaders:
Group: grp
Expires-At: exp
claims: Equals(`grp`, `admin`)
csrf: {}
```
```yaml tab="Kubernetes Secret"
apiVersion: v1
kind: Secret
metadata:
name: my-secret
stringData:
clientID: my-oidc-client-name
clientSecret: mysecret
```
## Configuration Options
| Field | Description | Default | Required |
|:------|:------------|:--------|:---------|
| `issuer` | Defines the URL to the OpenID Connect provider (for example, `https://accounts.google.com`). <br /> It should point to the server which provides the OpenID Connect configuration. | "" | Yes |
| `redirectUrl` | Defines the URL used by the OpenID Connect provider to redirect back to the middleware once the authorization is complete. (More information [here](#redirecturl)) | "" | Yes |
| `clientID` | Defines the unique client identifier for an account on the OpenID Connect provider, must be set when the `clientSecret` option is set. (More information [here](#clientid-clientsecret)) | "" | Yes |
| `clientSecret` | Defines the unique client secret for an account on the OpenID Connect provider, must be set when the `clientID` option is set. (More information [here](#clientid-clientsecret)) | "" | Yes |
| `claims` | Defines the claims to validate in order to authorize the request. <br /> The `claims` option can only be used with JWT-formatted token. (More information [here](#claims)) | "" | No |
| `usernameClaim` | Defines the claim that will be evaluated to populate the `clientusername` in the access logs. <br /> The `usernameClaim` option can only be used with JWT-formatted token.| "" | No |
| `forwardHeaders` | Defines the HTTP headers to add to requests and populates them with values extracted from the access token claims returned by the authorization server. <br /> Claims to be forwarded that are not found in the JWT result in empty headers. <br /> The `forwardHeaders` option can only be used with JWT-formatted token. | [] | No |
| `clientConfig.tls.ca` | PEM-encoded certificate bundle or a URN referencing a secret containing the certificate bundle used to establish a TLS connection with the authorization server (More information [here](#clientconfig)) | "" | No |
| `clientConfig.tls.cert` | PEM-encoded certificate or a URN referencing a secret containing the certificate used to establish a TLS connection with the Vault server (More information [here](#clientconfig)) | "" | No |
| `clientConfig.tls.key` | PEM-encoded key or a URN referencing a secret containing the key used to establish a TLS connection with the Vault server. (More information [here](#clientconfig)) | "" | No |
| `clientConfig.tls.insecureSkipVerify` | Disables TLS certificate verification when communicating with the authorization server. <br /> Useful for testing purposes but strongly discouraged for production. (More information [here](#clientconfig)) | "" | No |
| `clientConfig.timeoutSeconds` | Defines the time before giving up requests to the authorization server. | 5 | No |
| `clientConfig.maxRetries` | Defines the number of retries for requests to authorization server that fail. | 3 | No |
| `pkce` | Defines the Proof Key for Code Exchange as described in [RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636). | false | No |
| `discoveryParams` | A map of arbitrary query parameters to be added to the openid-configuration well-known URI during the discovery mechanism. | "" | No |
| `scopes` | The scopes to request. Must include `openid`. | openid | No |
| `authParams` | A map of the arbitrary query parameters to be passed to the Authentication Provider. <br />When a `prompt` key is set to an empty string in the AuthParams,the prompt parameter is not added to the OAuth2 authorization URL Which means the user won't be prompted for consent.| "" | No |
| `disableLogin` | Disables redirections to the authentication provider <br /> This can be useful for protecting APIs where redirecting to a login page is undesirable. | false | No |
| `loginUrl` | Defines the URL used to start authorization when needed. <br /> All other requests that are not already authorized will return a 401 Unauthorized. When left empty, all requests can start authorization. <br /> It can be a path (`/login` for example), a host and a path (`example.com/login`) or a complete URL (`https://example.com/login`). <br /> Only `http` and `https` schemes are supported.| "" | No |
| `logoutUrl` |Defines the URL on which the session should be deleted in order to log users out. <br /> It can be a path (`/logout` for example), a host and a path (`example.com/logout`) or a complete URL (`https://example.com/logout`). <br /> Only `http` and `https` schemes are supported.| "" | No |
| `postLoginRedirectUrl` |If set and used in conjunction with `loginUrl`, the middleware will redirect to this URL after successful login. <br /> It can be a path (`/after/login` for example), a host and a path (`example.com/after/login`) or a complete URL (`https://example.com/after/login`). <br /> Only `http` and `https` schemes are supported. | "" | No |
| `postLogoutRedirectUrl` | If set and used in conjunction with `logoutUrl`, the middleware will redirect to this URL after logout. <br /> It can be a path (`/after/logout` for example), a host and a path (`example.com/after/logout`) or a complete URL (`https://example.com/after/logout`). <br /> Only `http` and `https` schemes are supported. | "" | No |
| `backchannelLogoutUrl` | Defines the URL called by the OIDC provider when a user logs out (see https://openid.net/specs/openid-connect-rpinitiated-1_0.html#OpenID.BackChannel). <br /> It can be a path (`/backchannel-logout` for example), a host and a path (`example.com/backchannel-logout`) or a complete URL (`https://example.com/backchannel-logout`). <br /> Only `http` and `https` schemes are supported. <br /> This feature is currently in an experimental state and has been tested exclusively with the Keycloak OIDC provider. | "" | No |
| `backchannelLogoutSessionsRequired` | This specifies whether the OIDC provider includes the sid (session ID) Claim in the Logout Token to identify the user session (see https://openid.net/specs/openid-connect-backchannel-1_0.html#BCRegistration). <br/> If omitted, the default value is false. <br /> This feature is currently in an experimental state and has been tested exclusively with the Keycloak OIDC provider. | false | No |
| `stateCookie.name` | Defines the name of the state cookie. |"`MIDDLEWARE_NAME`-state" | No |
| `stateCookie.path` | Defines the URL path that must exist in the requested URL in order to send the Cookie header. <br /> The `%x2F` ('/') character is considered a directory separator, and subdirectories will match as well. <br /> For example, if `stateCookie.path` is set to `/docs`, these paths will match: `/docs`,`/docs/web/`,`/docs/web/http`.| "/" | No |
| `stateCookie.domain` | Defines the hosts that are allowed to receive the cookie. <br />If specified, then subdomains are always included. <br /> For example, if it is set to `example.com`, then cookies are included on subdomains like `api.example.com`. | "" | No |
| `stateCookie.maxAge` |Defines the number of seconds after which the state cookie should expire. <br /> A zero or negative number will expire the cookie immediately. | 600 | No |
| `stateCookie.sameSite` | Informsbrowsers how they should handle the state cookie on cross-site requests. <br /> Setting it to `lax` or `strict` can provide some protection against cross-site request forgery attacks ([CSRF](https://developer.mozilla.org/en-US/docs/Glossary/CSRF)). <br /> More information [here](#samesite---accepted-values). | lax | No |
| `stateCookie.httpOnly` | Forbids JavaScript from accessing the cookie. <br /> For example, through the `Document.cookie` property, the `XMLHttpRequest` API, or the `Request` API. <br /> This mitigates attacks against cross-site scripting ([XSS](https://developer.mozilla.org/en-US/docs/Glossary/XSS)). | true | No |
| `stateCookie.secure` | Defines whether the state cookie is only sent to the server when a request is made with the `https` scheme. | false | No |
| `session.name` | The name of the session cookie. |"`MIDDLEWARE_NAME`-session"| No |
| `session.path` | Defines the URL path that must exist in the requested URL in order to send the Cookie header. <br />The `%x2F` ('/'') character is considered a directory separator, and subdirectories will match as well. <br /> For example, if `stateCookie.path` is set to `/docs`, these paths will match: `/docs`,`/docs/web/`,`/docs/web/http`.| "/" | No |
| `session.domain` | Specifies the hosts that are allowed to receive the cookie. If specified, then subdomains are always included. If specified, then subdomains are always included. <br /> For example, if it is set to `example.com`, then cookies are included on subdomains like `api.example.com`.| "" | No |
| `session.expiry` | Number of seconds after which the session should expire. A zero or negative number is **prohibited**. | 86400 (24h) | No |
| `session.sliding` | Forces the middleware to renew the session cookie each time an authenticated request is received. | true | No |
| `session.refresh` | Enables the access token refresh when it expires. | true | No |
| `session.sameSite` | Inform browsers how they should handle the session cookie on cross-site requests. <br /> Setting it to `lax` or `strict` can provide some protection against cross-site request forgery attacks ([CSRF](https://developer.mozilla.org/en-US/docs/Glossary/CSRF)). <br /> More information [here](#samesite---accepted-values). | lax | No |
| `session.httpOnly` | Forbids JavaScript from accessing the cookie. <br /> For example, through the `Document.cookie` property, the `XMLHttpRequest` API, or the `Request` API. <br /> This mitigates attacks against cross-site scripting ([XSS](https://developer.mozilla.org/en-US/docs/Glossary/XSS)). | true | No |
| `session.secure` | Defines whether the session cookie is only sent to the server when a request is made with the `https` scheme. | false | No |
| `session.store.redis.endpoints` | Endpoints of the Redis instances to connect to (example: `redis.traefik-hub.svc.cluster.local:6379`) | "" | Yes |
| `session.store.redis.username` | The username Traefik Hub will use to connect to Redis | "" | No |
| `session.store.redis.password` | The password Traefik Hub will use to connect to Redis | "" | No |
| `session.store.redis.database` | The database Traefik Hub will use to sore information (default: `0`) | "" | No |
| `session.store.redis.cluster` | Enable Redis Cluster | "" | No |
| `session.store.redis.tls.caBundle` | Custom CA bundle | "" | No |
| `session.store.redis.tls.cert` | TLS certificate | "" | No |
| `session.store.redis.tls.key` | TLS key | "" | No |
| `session.store.redis.tls.insecureSkipVerify` | Allow skipping the TLS verification | "" | No |
| `session.store.redis.sentinel.masterSet` | Name of the set of main nodes to use for main selection. Required when using Sentinel. | "" | No |
| `session.store.redis.sentinel.username` | Username to use for sentinel authentication (can be different from `username`) | "" | No |
| `session.store.redis.sentinel.password` | Password to use for sentinel authentication (can be different from `password`) | "" | No |
| `csrf` | When enabled, a CSRF cookie, named `traefikee-csrf-token`, is bound to the OIDC session to protect service from CSRF attacks. <br /> It is based on the [Signed Double Submit Cookie](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#signed-double-submit-cookie) implementation as defined by the OWASP Foundation.<br />Moreinformation [here](#csrf). | "" | No |
| `csrf.secure` | Defines whether the CSRF cookie is only sent to the server when a request is made with the `https` scheme. | false | No |
| `csrf.headerName` | Defines the name of the header used to send the CSRF token value received previously in the CSRF cookie. | TraefikHub-Csrf-Token | No |
### redirectUrl
#### Add specific rule on the IngressRoute
The URL informs the OpenID Connect provider how to return to the middleware.
If the router rule is accepting all paths on a domain, no extra work is needed.
If the router rule is specific about the paths allowed, the path set in this option should be included.
```yaml tab="Defining specific rule for redirectUrl"
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
name: whoami
spec:
entryPoints:
- web
- websecure
routes:
# Rules to match the loginUrl and redirectUrl can be added into
# your current router.
- match: Path(`/myapi`) || Path(`/login`) || Path(`/callback`)
kind: Rule
middlewares:
- name: test-oidc
```
This URL will not be passed to the upstream application, but rather handled by the middleware itself.
The chosen URL should therefore not conflict with any URLs needed by the upstream application.
This URL sometimes needs to be set in the OpenID Connect Provider's configuration as well (like for Google Accounts for example).
It can be the absolute URL, relative to the protocol (inherits the request protocol), or relative to the domain (inherits the request domain and protocol).
See the following examples.
#### Inherit the Protocol and Domain from the Request and Uses the Redirecturls Path
| Request URL | RedirectURL| Result |
|:------------|:-----------|:-------|
| `http://expl.co` | `/cback` | `http://expl.co/cback` |
#### Inherit the Protocol from the Request and Uses the Redirecturls Domain and Path
| Request URL | RedirectURL| Result |
|:------------|:-----------|:-------|
| `https://scur.co` | `expl.co/cback`| `https://expl.co/cback` |
#### Replace the Request URL with the Redirect URL since It Is an Absolute URL
| Request URL | RedirectURL| Result |
|:------------|:-----------|:-------|
| `https://scur.co` | `http://expl.co/cback` | `http://expl.co/cback` |
!!! note "Supported Schemes"
Only `http` and `https` schemes are supported.
```yaml tab="Defining the redirectUrl"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-oidc
spec:
plugin:
oidc:
issuer: "https://tenant.auth0.com/realms/myrealm"
redirectUrl: "/callback"
clientID: my-oidc-client-name
clientSecret: mysecret
```
### clientID, clientSecret
#### Storing secret values in Kubernetes secrets
When configuring the `clientID` and the `clientSecret`, it is possible to reference Kubernetes secrets defined in the same namespace as the Middleware.
The reference to a Kubernetes secret takes the form of a URN:
```text
urn:k8s:secret:[name]:[valueKey]
```
### claims
#### Syntax
The following functions are supported in `claims`:
| Function | Description | Example |
|-------------------|--------------------|-----------------|
| Equals | Validates the equality of the value in `key` with `value`. | Equals(\`grp\`, \`admin\`) |
| Prefix | Validates the value in `key` has the prefix of `value`. | Prefix(\`referrer\`, \`http://example.com\`) |
| Contains (string) | Validates the value in `key` contains `value`. | Contains(\`referrer\`, \`/foo/\`) |
| Contains (array) | Validates the `key` array contains the `value`. | Contains(\`areas\`, \`home\`) |
| SplitContains | Validates the value in `key` contains the `value` once split by the separator. | SplitContains(\`scope\`, \` \`, \`writer\`) |
| OneOf | Validates the `key` array contains one of the `values`. | OneOf(\`areas\`, \`office\`, \`lab\`) |
All functions can be joined by boolean operands. The supported operands are:
| Operand | Description | Example |
|---------|--------------------|-----------------|
| && | Compares two functions and returns true only if both evaluate to true. | Equals(\`grp\`, \`admin\`) && Equals(\`active\`, \`true\`) |
| \|\| | Compares two functions and returns true if either evaluate to true. | Equals(\`grp\`, \`admin\`) \|\| Equals(\`active\`, \`true\`) |
| ! | Returns false if the function is true, otherwise returns true. | !Equals(\`grp\`, \`testers\`) |
All examples will return true for the following data structure:
```json tab="JSON"
{
"active": true,
"grp": "admin",
"scope": "reader writer deploy",
"referrer": "http://example.com/foo/bar",
"areas": [
"office",
"home"
]
}
```
#### Nested Claims
Nested claims are supported by using a `.` between keys. For example:
```bash tab="Key"
user.name
```
```json tab="Claims"
{
"active": true,
"grp": "admin",
"scope": "reader writer deploy",
"referrer": "http://example.com/foo/bar",
"areas": [
"office",
"home"
],
"user" {
"name": "John Snow",
"status": "undead"
}
}
```
```bash tab="Result"
John Snow
```
!!! note "Handling keys that contain a '.'"
If the `key` contains a dot, the dot can be escaped using `\.`
!!! note "Handling a key that contains a '\'"
If the `key` contains a `\`, it needs to be doubled `\\`.
!!! note "Access Token and ID Token claims"
The first argument of the function, which represents the key to look for in the token claims, can be prefixed to specify which of the two kinds of token is inspected.
Possible prefix values are `id_token.` and `access_token.`. If no prefix is specified, it defaults to the ID token.
| Example | Description |
| ----------------------------------------- | ------------------------------------------------------------------------------ |
| Equals(\`id_token.grp\`, \`admin\`) | Checks if the value of claim `grp` in the ID token is `admin`. |
| Prefix(\`access_token.referrer\`, \`http://example.com\`) | Checks if the value of claim `referrer` in the access token is prefixed by `http://example.com\`.|
| OneOf(\`areas\`, \`office\`, \`lab\`) | Checks if the value of claim `areas` in the ID token is `office` or `labs`. |
### clientConfig
Defines the configuration used to connect the API Gateway to a Third Party Software such as an Identity Provider.
#### `clientConfig.tls`
##### Storing secret values in Kubernetes secrets
When configuring the `tls.ca`, `tls.cert`, `tls.key`, it is possible to reference Kubernetes secrets defined in the same namespace as the Middleware.
The reference to a Kubernetes secret takes the form of a URN:
```text
urn:k8s:secret:[name]:[valueKey]
```
```yaml tab="Middleware JWT"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-oidc
spec:
plugin:
oidc:
clientConfig:
tls:
ca: "urn:k8s:secret:tls:ca"
cert: "urn:k8s:secret:tls:cert"
key: "urn:k8s:secret:tls:key"
insecureSkipVerify: true
```
```yaml tab="Kubernetes TLS Secret"
apiVersion: v1
kind: Secret
metadata:
name: tls
stringData:
ca: |-
-----BEGIN CERTIFICATE-----
MIIB9TCCAWACAQAwgbgxGTAXBgNVBAoMEFF1b1ZhZGlzIExpbWl0ZWQxHDAaBgNV
BAsME0RvY3VtZW50IERlcGFydG1lbnQxOTA3BgNVBAMMMFdoeSBhcmUgeW91IGRl
Y29kaW5nIG1lPyAgVGhpcyBpcyBvbmx5IGEgdGVzdCEhITERMA8GA1UEBwwISGFt
aWx0b24xETAPBgNVBAgMCFBlbWJyb2tlMQswCQYDVQQGEwJCTTEPMA0GCSqGSIb3
DQEJARYAMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJ9WRanG/fUvcfKiGl
EL4aRLjGt537mZ28UU9/3eiJeJznNSOuNLnF+hmabAu7H0LT4K7EdqfF+XUZW/2j
RKRYcvOUDGF9A7OjW7UfKk1In3+6QDCi7X34RE161jqoaJjrm/T18TOKcgkkhRzE
apQnIDm0Ea/HVzX/PiSOGuertwIDAQABMAsGCSqGSIb3DQEBBQOBgQBzMJdAV4QP
Awel8LzGx5uMOshezF/KfP67wJ93UW+N7zXY6AwPgoLj4Kjw+WtU684JL8Dtr9FX
ozakE+8p06BpxegR4BR3FMHf6p+0jQxUEAkAyb/mVgm66TyghDGC6/YkiKoZptXQ
98TwDIK/39WEB/V607As+KoYazQG8drorw==
-----END CERTIFICATE-----
cert: |-
-----BEGIN CERTIFICATE-----
MIIB9TCCAWACAQAwgbgxGTAXBgNVBAoMEFF1b1ZhZGlzIExpbWl0ZWQxHDAaBgNV
BAsME0RvY3VtZW50IERlcGFydG1lbnQxOTA3BgNVBAMMMFdoeSBhcmUgeW91IGRl
Y29kaW5nIG1lPyAgVGhpcyBpcyBvbmx5IGEgdGVzdCEhITERMA8GA1UEBwwISGFt
aWx0b24xETAPBgNVBAgMCFBlbWJyb2tlMQswCQYDVQQGEwJCTTEPMA0GCSqGSIb3
DQEJARYAMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJ9WRanG/fUvcfKiGl
EL4aRLjGt537mZ28UU9/3eiJeJznNSOuNLnF+hmabAu7H0LT4K7EdqfF+XUZW/2j
RKRYcvOUDGF9A7OjW7UfKk1In3+6QDCi7X34RE161jqoaJjrm/T18TOKcgkkhRzE
apQnIDm0Ea/HVzX/PiSOGuertwIDAQABMAsGCSqGSIb3DQEBBQOBgQBzMJdAV4QP
Awel8LzGx5uMOshezF/KfP67wJ93UW+N7zXY6AwPgoLj4Kjw+WtU684JL8Dtr9FX
ozakE+8p06BpxegR4BR3FMHf6p+0jQxUEAkAyb/mVgm66TyghDGC6/YkiKoZptXQ
98TwDIK/39WEB/V607As+KoYazQG8drorw==
-----END CERTIFICATE-----
key: |-
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIC8CsJ/B115S+JtR1/l3ZQwKA3XdXt9zLqusF1VXc/KloAoGCCqGSM49
AwEHoUQDQgAEpwUmRIZHFt8CdDHYm1ikScCScd2q6QVYXxJu+G3fQZ78ScGtN7fu
KXMnQqVjXVRAr8qUY8yipVKuMCepnPXScQ==
-----END EC PRIVATE KEY-----
```
### sameSite - Accepted values
- `none`: Thebrowser will send cookies with both cross-site requests and same-site requests.
- `strict`: Thebrowser will only send cookies for same-site requests (requests originating from the site that set the cookie).
If the request originated from a different URL than the URL of the current location, none of the cookies tagged with the `strict` attribute will be included.
- `lax`: Same-site cookies are withheld on cross-site subrequests, such as calls to load images or frames, but will be sent when a user navigates to the URL from an external site; for example, by following a link.
### session.store
An OpenID Connect Authentication middleware can use a persistent KV storage to store the `HTTP` sessions data
instead of keeping all the state in cookies.
It avoids cookies growing inconveniently large, which can lead to latency issues.
Refer to the [redis options](#configuration-options) to configure the Redis connection.
Connection parameters to your [Redis](https://redis.io/ "Link to website of Redis") server are attached to your Middleware deployment.
The following Redis modes are supported:
- Single instance mode
- [Redis Cluster](https://redis.io/docs/management/scaling "Link to official Redis documentation about Redis Cluster mode")
- [Redis Sentinel](https://redis.io/docs/management/sentinel "Link to official Redis documentation about Redis Sentinel mode")
!!! info
If you use Redis in single instance mode or Redis Sentinel, you can configure the `database` field.
This value won't be taken into account if you use Redis Cluster (only database `0` is available).
In this case, a warning is displayed, and the value is ignored.
For more information about Redis, we recommend the [official Redis documentation](https://redis.io/docs/ "Link to official Redis documentation").
```yaml tab="Defining Redis connection"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: test-oidc
spec:
plugin:
oidc:
issuer: "https://tenant.auth0.com/realms/myrealm"
redirectUrl: "/callback"
clientID: my-oidc-client-name
clientSecret: mysecret
session:
store:
redis:
endpoints:
- redis-master.traefik-hub.svc.cluster.local:6379
password: "urn:k8s:secret:oidc:redisPass"
```
```yaml tab="Creating the Kubernetes secret"
apiVersion: v1
kind: Secret
metadata:
name: oidc
stringData:
redisPass: mysecret12345678
```
### csrf
#### CSRF Internal Behavior
When the OIDC session is expired, the corresponding CSRF cookie is deleted.
This means that a new CSRF token will be generated and sent to the client whenever the session is refreshed or recreated.
When a request is sent and uses a non-safe method (see [RFC7231#section-4.2.1](https://datatracker.ietf.org/doc/html/rfc7231.html#section-4.2.1)),
the CSRF token value (extracted from the cookie) have to be sent to the server in the header configured with the [headerName option](#configuration-options).
{!traefik-for-business-applications.md!}

View File

@ -0,0 +1,72 @@
---
title: 'Open Policy Agent'
description: 'Traefik Hub API Gateway - The Open Policy Agent (OPA) middleware that allows you to restrict access to your services.'
---
!!! info "Traefik Hub Feature"
This middleware is available exclusively in [Traefik Hub](https://traefik.io/traefik-hub/). Learn more about [Traefik Hub's advanced features](https://doc.traefik.io/traefik-hub/api-gateway/intro).
Traefik Hub comes with an Open Policy Agent middleware that allows you to restrict access to your services. It also allows you to enrich request headers with data extracted from policies.
The OPA middleware works as an [OPA agent](https://www.openpolicyagent.org/).
!!! note "OPA Version"
This middleware uses the [v1.3.0 of the OPA specification](https://www.openpolicyagent.org/docs).
## Configuration Example
```yaml tab="Allow requests with specific JWT claim"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: opa-allow-jwt-claim
namespace: apps
spec:
plugin:
opa:
policy: |
package example.policies
allow {
[_, encoded] := split(input.headers.Authorization, " ")
[header, payload, signature] = io.jwt.decode(encoded)
payload["email"] == "bibi@example.com"
}
forwardHeaders:
Group: data.package.grp
```
```yaml tab="Deny requests with JSON Accept Header"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: opa-deny-json
namespace: apps
spec:
plugin:
opa:
policy: |
package example.policies
default allow = false
json_content {
input.headers["Accept"] == "application/json"
}
allow {
not json_content
}
allow: data.example.policies.allow
```
## Configuration Options
| Field | Description | Default | Required |
|:---------|-----------------------|:--------|:----------------------------|
| `policy` | Path or the content of a [policy file](https://www.openpolicyagent.org/docs/v0.66.0/kubernetes-primer/#writing-policies). | "" | No (one of `policy` or `bundlePath` must be set) |
| `bundlePath` | The `bundlePath` option should contain the path to an OPA [bundle](https://www.openpolicyagent.org/docs/v0.66.0/management-bundles/). | "" | No (one of `policy` or `bundlePath` must be set) |
| `allow` | The `allow` option sets the expression to evaluate that determines if the request should be authorized. | "" | No (one of `allow` or `forwardHeaders` must be set) |
| `forwardHeaders` | The `forwardHeaders` option sets the HTTP headers to add to requests and populates them with the result of the given expression. | "" | No (one of `allow` or `forwardHeaders` must be set) |
{!traefik-for-business-applications.md!}

View File

@ -0,0 +1,64 @@
---
title: 'Coraza Web Application Firewall'
description: 'Traefik Hub API Gateway - The HTTP Coraza in Traefik Hub API Gateway provides web application firewall capabilities'
---
!!! info "Traefik Hub Feature"
This middleware is available exclusively in [Traefik Hub](https://traefik.io/traefik-hub/). Learn more about [Traefik Hub's advanced features](https://doc.traefik.io/traefik-hub/api-gateway/intro).
The [Coraza WAF](https://coraza.io/) middleware in Traefik Hub API Gateway provides web application firewall capabilities.
The native middleware in Hub API Gateway provides at least 23 times more performance compared to the
WASM-based [Coraza plugin](https://plugins.traefik.io/plugins/65f2aea146079255c9ffd1ec/coraza-waf) available with the open-source Traefik Proxy.
To learn how to write rules, please visit [Coraza documentation](https://coraza.io/docs/tutorials/introduction/ "Link to Coraza introduction tutorial") and
[OWASP CRS documentation](https://coreruleset.org/docs/ "Link to the OWAP CRS project documentation").
!!! warning
Starting with Traefik Hub v3.11.0, Coraza needs to have read/write permissions to `/tmp`. This is related to [this upstream PR](https://github.com/corazawaf/coraza/pull/1030).
---
## Configuration Examples
```yaml tab="Deny the /admin path"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: waf
spec:
plugin:
coraza:
directives:
- SecRuleEngine On
- SecRule REQUEST_URI "@streq /admin" "id:101,phase:1,t:lowercase,log,deny"
```
```yaml tab="Allow only GET methods"
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: wafcrs
namespace: apps
spec:
plugin:
coraza:
crsEnabled: true
directives:
- SecDefaultAction "phase:1,log,auditlog,deny,status:403"
- SecDefaultAction "phase:2,log,auditlog,deny,status:403"
- SecAction "id:900110, phase:1, pass, t:none, nolog, setvar:tx.inbound_anomaly_score_threshold=5, setvar:tx.outbound_anomaly_score_threshold=4"
- SecAction "id:900200, phase:1, pass, t:none, nolog, setvar:'tx.allowed_methods=GET'"
- Include @owasp_crs/REQUEST-911-METHOD-ENFORCEMENT.conf
- Include @owasp_crs/REQUEST-949-BLOCKING-EVALUATION.conf
```
## Configuration Options
| Field | Description | Default | Required |
|:---------|:-----------------------|:--------|:----------------------------|
| `directives` | List of WAF rules to enforce. | | Yes |
| `crsEnabled` | Enable [CRS rulesets](https://github.com/corazawaf/coraza-coreruleset/tree/main/rules/%40owasp_crs).<br /> Once the ruleset is enabled, it can be used in the middleware. | false | False |
{!traefik-for-business-applications.md!}

View File

@ -33,6 +33,9 @@ extra_javascript:
- assets/js/hljs/highlight.pack.js # Download from https://highlightjs.org/download/ and enable YAML, TOML and Dockerfile
- assets/js/extra.js
extra_css:
- assets/css/menu-icons.css
plugins:
- search
- exclude:
@ -270,6 +273,7 @@ nav:
- 'Middlewares' :
- 'Overview' : 'reference/routing-configuration/http/middlewares/overview.md'
- 'AddPrefix' : 'reference/routing-configuration/http/middlewares/addprefix.md'
- '<span class="nav-link-with-icon">APIKey <img src="https://doc.traefik.io/traefik-hub/img/ps-traefik-hub-logo-light.svg" class="menu-icon" alt="Traefik Hub API Gateway"></span>' : 'reference/routing-configuration/http/middlewares/apikey.md'
- 'BasicAuth' : 'reference/routing-configuration/http/middlewares/basicauth.md'
- 'Buffering': 'reference/routing-configuration/http/middlewares/buffering.md'
- 'Chain': 'reference/routing-configuration/http/middlewares/chain.md'
@ -281,8 +285,15 @@ nav:
- 'ForwardAuth': 'reference/routing-configuration/http/middlewares/forwardauth.md'
- 'GrpcWeb': 'reference/routing-configuration/http/middlewares/grpcweb.md'
- 'Headers': 'reference/routing-configuration/http/middlewares/headers.md'
- '<span class="nav-link-with-icon">HMAC <img src="https://doc.traefik.io/traefik-hub/img/ps-traefik-hub-logo-light.svg" class="menu-icon" alt="Traefik Hub API Gateway"></span>' : 'reference/routing-configuration/http/middlewares/hmac.md'
- 'IPAllowList': 'reference/routing-configuration/http/middlewares/ipallowlist.md'
- 'InFlightReq': 'reference/routing-configuration/http/middlewares/inflightreq.md'
- '<span class="nav-link-with-icon">JWT <img src="https://doc.traefik.io/traefik-hub/img/ps-traefik-hub-logo-light.svg" class="menu-icon" alt="Traefik Hub API Gateway"></span>' : 'reference/routing-configuration/http/middlewares/jwt.md'
- '<span class="nav-link-with-icon">LDAP <img src="https://doc.traefik.io/traefik-hub/img/ps-traefik-hub-logo-light.svg" class="menu-icon" alt="Traefik Hub API Gateway"></span>' : 'reference/routing-configuration/http/middlewares/ldap.md'
- '<span class="nav-link-with-icon">Token Introspection <img src="https://doc.traefik.io/traefik-hub/img/ps-traefik-hub-logo-light.svg" class="menu-icon" alt="Traefik Hub API Gateway"></span>' : 'reference/routing-configuration/http/middlewares/oauth2-token-introspection.md'
- '<span class="nav-link-with-icon">Client Credentials <img src="https://doc.traefik.io/traefik-hub/img/ps-traefik-hub-logo-light.svg" class="menu-icon" alt="Traefik Hub API Gateway"></span>' : 'reference/routing-configuration/http/middlewares/oauth2-client-credentials.md'
- '<span class="nav-link-with-icon">OIDC <img src="https://doc.traefik.io/traefik-hub/img/ps-traefik-hub-logo-light.svg" class="menu-icon" alt="Traefik Hub API Gateway"></span>' : 'reference/routing-configuration/http/middlewares/oidc.md'
- '<span class="nav-link-with-icon">OPA <img src="https://doc.traefik.io/traefik-hub/img/ps-traefik-hub-logo-light.svg" class="menu-icon" alt="Traefik Hub API Gateway"></span>' : 'reference/routing-configuration/http/middlewares/opa.md'
- 'PassTLSClientCert': 'reference/routing-configuration/http/middlewares/passtlsclientcert.md'
- 'RateLimit': 'reference/routing-configuration/http/middlewares/ratelimit.md'
- 'RedirectRegex': 'reference/routing-configuration/http/middlewares/redirectregex.md'
@ -292,6 +303,7 @@ nav:
- 'Retry': 'reference/routing-configuration/http/middlewares/retry.md'
- 'StripPrefix': 'reference/routing-configuration/http/middlewares/stripprefix.md'
- 'StripPrefixRegex': 'reference/routing-configuration/http/middlewares/stripprefixregex.md'
- '<span class="nav-link-with-icon">WAF <img src="https://doc.traefik.io/traefik-hub/img/ps-traefik-hub-logo-light.svg" class="menu-icon" alt="Traefik Hub API Gateway"></span>' : 'reference/routing-configuration/http/middlewares/waf.md'
- 'TCP' :
- 'Router' :
- 'Rules & Priority' : 'reference/routing-configuration/tcp/router/rules-and-priority.md'