Authentication
The gateway can validate tokens before forwarding a request: signed JWTs, encrypted JWTs (JWE) and opaque tokens checked by your identity provider. A request whose token is missing or invalid gets 401 Unauthorized and never reaches the backend, unless the method sets AllowAnonymous (only a missing token can be let through, an invalid or expired one is always refused). A request whose token is valid but lacks a required scope gets 403 Forbidden.
Every request the gateway forwards tells the backend whether it was authenticated, with the X-Nocleye-Authenticated header. See Headers sent to the backend.
Authentication methods are defined under AuthMethods and bound by name with AuthMethod on GlobalConfig, a server or a route. The closest scope wins: route, then server, then global. Routes with no authentication method are public.
An authentication method says how a token is checked. What a token must be allowed to do is set where the method is used, with RequiredScopes, so one method can be defined once and reused with different rules.
AuthMethods: secure-hs256-bearer: Mode: Bearer SigningMethod: HS256 KeyRef: "file:hs256.key" IdClaimName: sub
secure-hs512-raw: Mode: RawHeader SigningMethod: HS512 HeaderName: X-Auth-Token KeyRef: "env:HS512_SECRET" IdClaimName: sub
ServerRoutes: a-secure: TargetServer: svc-a MatchOptions: PathPattern: /a/secure AuthMethod: secure-hs256-bearerOptions
Section titled “Options”| Key | Required | Description |
|---|---|---|
Mode |
yes | How the token is read and checked: Bearer, RawHeader, JWE, OAuth2 or OAuth2Introspection. |
SigningMethod |
Bearer, RawHeader |
Algorithm the token must be signed with. |
KeyRef |
Bearer, RawHeader, JWE |
Where the verification key (for JWE, the decryption key) comes from. See Keys. |
HeaderName |
RawHeader, JWE |
Header that carries the token. |
IdClaimName |
no | Name of the token claim that identifies the caller, e.g. sub. |
Issuer |
no | When set, the token’s iss claim must match. |
Audience |
no | When set, the token’s aud claim must contain this value. |
AllowAnonymous |
no | true lets a request without a credential through as anonymous. Default false: it gets 401. See Anonymous requests. |
RemoveCredentialHeader |
no | true removes the credential header before the request is forwarded. Default false: the credential is forwarded. See Headers sent to the backend. |
ForwardClaims |
no | Map of token claim name to header suffix. Each claim is sent to the backend as X-Nocleye-Claim-<suffix>. See Forwarding claims. |
These three keys work the same in every Mode.
| Mode | Token location |
|---|---|
Bearer |
The Authorization header, in the form Authorization: Bearer <token>. The Bearer word is not case-sensitive, bearer <token> works too. |
RawHeader |
The header named in HeaderName, containing the bare token, e.g. X-Auth-Token: <token>. |
JWE |
The header named in HeaderName, containing an encrypted token (JWE compact form). See JWE. |
OAuth2 |
Like Bearer, but the verification keys are downloaded from your identity provider. It can also accept encrypted tokens. See OAuth2 (JWKS). |
OAuth2Introspection |
Like Bearer, but the token is opaque and your identity provider is asked whether it is valid. See OAuth2 introspection. |
Signing methods
Section titled “Signing methods”SigningMethod |
Algorithm | Key |
|---|---|---|
HS256, HS384, HS512 |
HMAC with SHA-2 | Shared secret |
RS256, RS384, RS512 |
RSA PKCS#1 v1.5 | PEM public key |
PS256, PS384, PS512 |
RSA-PSS | PEM public key |
ES256, ES384, ES512 |
ECDSA with P-256, P-384 or P-521 | PEM public key on the matching curve |
EdDSA |
Ed25519 | PEM public key, or the raw 32 byte key |
In OAuth2 mode the keys come from the JWKS and HS* is not allowed (see OAuth2 (JWKS)).
A token signed with a different algorithm than the one configured is rejected.
KeyRef must start with env: or file::
| Form | Meaning |
|---|---|
env:NAME |
The key is the value of the environment variable NAME. |
file:name |
The key is the content of the file name inside /etc/nocleye-beta/gateway/auths/. Only that folder is read: absolute paths, .. and symlinks pointing outside it are rejected. |
Keys are loaded when the gateway starts. The gateway refuses to start if a key can’t be read or doesn’t match the signing method, nocleye check does not read key files.
OAuth2 (JWKS)
Section titled “OAuth2 (JWKS)”With Mode: OAuth2 the gateway verifies tokens issued by an identity provider (Auth0, Keycloak, Entra ID, Okta, …). The provider publishes its public keys at a JWKS URL and rotates them from time to time. The gateway keeps a copy of those keys in memory, so checking a request never waits on the network.
AuthMethods: corp-sso: Mode: OAuth2 JWKSUri: https://idp.example.com/.well-known/jwks.json Algorithms: [RS256] Issuer: https://idp.example.com/ Audience: my-api IdClaimName: sub| Key | Required | Description |
|---|---|---|
JWKSUri |
no | https URL where the provider publishes its keys. When left out, the gateway finds it through discovery using Issuer. |
Algorithms |
yes | Algorithms you accept: RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512 or EdDSA. HS* is not allowed. A token using any other algorithm, or none, is rejected. |
Issuer |
yes | The token’s iss claim must match. |
Audience |
yes | The token’s aud claim must contain this value. |
JWKSRefreshInterval |
no | How often the keys are downloaded again. Default 1h. |
JWKSMinRefetchInterval |
no | Minimum time between downloads triggered by unknown key ids. Default 30s. |
JWKSFetchTimeout |
no | Timeout for one download. Default 5s. |
ClockSkew |
no | Tolerance on exp, nbf and iat. Default 30s. |
JWKSMaxStale |
no | If the keys could not be refreshed for longer than this, tokens are rejected (401) instead of being checked with keys the provider may have revoked. Default 24h; it can’t be turned off. |
RequiredClaims |
no | Map of claim name to value. A string claim must equal it; an array claim must contain it. |
RequiredTokenType |
no | Required value of the token’s typ header, e.g. at+jwt (RFC 9068). Use it to stop ID tokens being accepted as access tokens. Your provider must set the header. If you set neither this nor RequiredClaims, and no route using the method requires scopes, nocleye check warns that any token with the right iss and aud is accepted. |
MaxTokenAge |
no | Reject tokens issued (iat) longer ago than this, or without iat. Default: off. |
Decryption |
no | Accept encrypted access tokens too. See Encrypted access tokens. |
IdClaimName works as in the other modes. Durations are written like 30s, 5m, 1h.
Example with the optional checks:
AuthMethods: corp-sso: Mode: OAuth2 Issuer: https://idp.example.com # JWKSUri found through discovery Algorithms: [RS256] Audience: my-api RequiredTokenType: at+jwt RequiredClaims: tenant: acme MaxTokenAge: 8h JWKSMaxStale: 24hThe scopes the token must hold are not part of the method, see Required scopes.
Discovery
Section titled “Discovery”If JWKSUri is empty, the gateway downloads <Issuer>/.well-known/openid-configuration and uses its jwks_uri. Issuer must then be an https URL, and the issuer inside that document must be exactly equal to it, otherwise it is rejected. The discovery document is subject to the same rules as the keys (https only, no redirects to another host, 1 MiB limit) and is read again on every refresh.
How it behaves:
- The keys are downloaded when the gateway loads the config. If the URL can’t be reached or doesn’t return usable keys, the config is not applied: on a live swap the previous config keeps serving. When the gateway starts, it retries for up to 30 seconds (in case the provider comes up after it) and then refuses to start.
- Keys are refreshed in the background every
JWKSRefreshInterval. If a refresh fails, the previous keys keep being used and a warning is logged. - When a token arrives signed with a key id (
kid) the gateway doesn’t know, it downloads the keys once more (at most once perJWKSMinRefetchInterval, and once for any number of simultaneous requests) in case the provider rotated its keys. Tokens with a key id that is still unknown are rejected with401. - Only the URL in
JWKSUriis ever contacted. URLs inside the token (jku,x5u) are ignored. Redirects to another host are refused, and responses larger than 1 MiB are rejected. Keys that are weak (RSA under 2048 bits), symmetric, have nokid, or whoseuseis notsigare ignored. - Each config load (including a live swap) downloads the keys again, so for a short moment two loaded configs may both poll the URL.
nocleye check also downloads the JWKS URL and reports an error if it doesn’t answer with HTTP 200, isn’t a JWKS document, or has no signing keys, so a wrong URL is found before you deploy. Pass --offline to skip it. See cli.md. The live config API does the same check and rejects the config with 400. The response includes the reason (for example the HTTP status or the connection error), so you can fix the URL or your network.
Encrypted access tokens
Section titled “Encrypted access tokens”Some providers encrypt access tokens (a JWE whose content is the signed JWT) so that clients can’t read the claims. Add a Decryption block and OAuth2 mode accepts them: the token is decrypted with your private key, and the signed JWT inside goes through the same checks as any other token (keys from the JWKS, Algorithms, Issuer, Audience, …).
AuthMethods: corp-sso: Mode: OAuth2 Issuer: https://idp.example.com Algorithms: [RS256] Audience: my-api Decryption: KeyRef: "file:jwe-private.pem" KeyManagementAlgs: [RSA-OAEP-256] ContentEncryptionAlgs: [A256GCM]| Key | Required | Description |
|---|---|---|
KeyRef |
yes | Your private key, as in Keys: a PEM (PKCS#8, PKCS#1 or SEC1) for RSA-OAEP-256 and ECDH-ES*, the raw secret for A256KW and dir. |
KeyManagementAlgs |
yes | Accepted JWE alg values: RSA-OAEP-256, ECDH-ES, ECDH-ES+A256KW, A256KW or dir. All of them must use the same kind of key (RSA, EC or symmetric). |
ContentEncryptionAlgs |
yes | Accepted JWE enc values: A128GCM, A256GCM, A128CBC-HS256 or A256CBC-HS512. |
- Both lists are allowlists: a token naming any other algorithm is rejected before it is decrypted.
- The content must be a signed JWT. Encrypted claims without a signature are rejected, since anyone holding your public key could create them.
- Plain signed tokens are still accepted, so you can move your provider to encrypted tokens without downtime.
- Encrypted tokens over 32 KiB, or that decrypt to more than 32 KiB, are rejected.
- The key is read when the gateway loads the config, a key that can’t be read or doesn’t fit
KeyManagementAlgsstops the load.
Mode: JWE is for a token encrypted with a key you control, sent in a header of your choice, and checked without an identity provider. The token is a JWE in compact form (five parts separated by dots).
AuthMethods: partner-jwe: Mode: JWE HeaderName: X-Auth-Encrypted KeyRef: "file:jwe-private.pem" KeyManagementAlg: RSA-OAEP-256 ContentEncryptionAlg: A256GCM NestedSigningMethod: RS256 NestedKeyRef: "file:issuer-public.pem" Issuer: https://issuer.example.com IdClaimName: sub| Key | Required | Description |
|---|---|---|
HeaderName |
yes | Header that carries the JWE. |
KeyRef |
yes | The decryption key, see Keys. A PEM private key for RSA-OAEP-256 and ECDH-ES*, the raw secret for A256KW and dir. |
KeyManagementAlg |
yes | The only accepted JWE alg: RSA-OAEP-256, ECDH-ES, ECDH-ES+A256KW, A256KW or dir. |
ContentEncryptionAlg |
yes | The only accepted JWE enc: A128GCM, A256GCM, A128CBC-HS256 or A256CBC-HS512. |
NestedSigningMethod, NestedKeyRef |
no, set together | The decrypted content is a JWT signed with this method, verified with this key (a signing method and its public key or secret). Strongly recommended. |
Issuer, Audience |
no | Checked against the claims inside the token. |
IdClaimName |
no | As in the other modes. |
Without NestedSigningMethod the content is read as plain JSON claims. Encryption alone doesn’t prove who made the token: anyone who knows your public key can encrypt claims to it. nocleye check warns about this.
A token that can’t be decrypted is always rejected with 401.
OAuth2 introspection (opaque tokens)
Section titled “OAuth2 introspection (opaque tokens)”Some providers issue opaque tokens: random strings that carry no claims. With Mode: OAuth2Introspection the gateway sends the token to the provider’s introspection endpoint (RFC 7662) and uses the answer.
AuthMethods: opaque-sso: Mode: OAuth2Introspection IntrospectionUri: https://idp.example.com/oauth2/introspect ClientId: my-gateway ClientSecretRef: "env:INTROSPECTION_SECRET" Audience: my-api IdClaimName: sub| Key | Required | Description |
|---|---|---|
IntrospectionUri |
yes | https URL of the introspection endpoint. |
ClientId |
not with bearer style |
The gateway’s client id at the provider. |
ClientSecretRef |
yes | Where the client secret comes from: env:NAME or file:name, as in Keys. The secret itself is never written in the config. |
IntrospectionAuthStyle |
no | How the gateway authenticates: basic (default, HTTP Basic), post (client_id and client_secret in the request body) or bearer (ClientSecretRef holds a bearer token). |
Audience |
yes | The response’s aud must contain this value. |
Issuer |
no | When set, the response’s iss must match. |
RequiredClaims |
no | Map of claim name to value, as in OAuth2. |
ClockSkew |
no | Tolerance on exp and nbf. Default 30s. |
IntrospectionTimeout |
no | Timeout for one request. Default 3s. |
IntrospectionCacheTTL |
no | How long an answer saying the token is active is reused. Default 1m. It is never kept past the token’s exp. |
IntrospectionNegativeCacheTTL |
no | How long a refusal is reused. Default 5s. |
IntrospectionCacheMaxEntries |
no | Maximum number of cached answers. Default 10000. |
IdClaimName works as in the other modes, and the answer’s fields (sub, scope, client_id, …) are the claims.
How it behaves:
- A token is accepted only if the answer says
"active": trueand passes theexp,nbf,iss,audandRequiredClaimschecks. - The gateway fails closed. If the endpoint can’t be reached, times out, answers with anything but HTTP 200 or sends something that isn’t a valid answer, the token is rejected with
401. Failures are never cached, the next request asks again. - Answers are cached to spare the provider, so a token revoked at the provider can still be accepted for up to
IntrospectionCacheTTL. Lower it if you need revocation to take effect sooner. - Concurrent requests with the same token share a single introspection request.
- The cache is keyed by a hash of the token, the token itself is never kept. Its size is capped by
IntrospectionCacheMaxEntries. - The endpoint receives the token and the client credentials, so only
httpsis accepted and redirects are never followed. - The endpoint isn’t contacted when the config loads, so a provider that is down at startup doesn’t keep the gateway down. The client secret is read at load: if it can’t be read, the config is not applied.
gw_introspection_totalcounts the outcomes, see observability.
Anonymous requests
Section titled “Anonymous requests”By default a request without a credential gets 401. With AllowAnonymous: true the caller may bring a token or not: with a valid token it is authenticated as usual, without one it continues as anonymous.
AuthMethods: optional-bearer: Mode: Bearer SigningMethod: HS256 KeyRef: "file:hs256.key" IdClaimName: sub AllowAnonymous: true- Only a missing credential is anonymous. A token that is present but expired, malformed or badly signed is always
401, in every mode.expandnbfare always enforced. - It works the same in every
Mode(Bearer,RawHeader,JWE,OAuth2,OAuth2Introspection). - The backend receives
X-Nocleye-Authenticated: false, no claim headers and noX-Nocleye-User-Id(the IP is not a user id). - Anonymous callers are usage controlled by their client IP, with a limiter key of their own (
anon:<ip>) that is separate from authenticated callers. They are limited, never skipped. - A route that sets
RequiredScopesanswers anonymous callers403withinsufficient_scope, since they hold no scopes.nocleye checkwarns about this combination. - There is no fallback identification key (a header or query value used instead of the IP) yet. The client IP is always used.
nocleye check warns about every method with AllowAnonymous, because anonymous traffic reaches the backend.
Headers sent to the backend
Section titled “Headers sent to the backend”X-Nocleye-Authenticated
Section titled “X-Nocleye-Authenticated”The gateway sets X-Nocleye-Authenticated on every proxied request (HTTP, each gRPC call and the WebSocket handshake), including routes with no authentication method:
| Value | When |
|---|---|
true |
The route’s authentication method validated a credential. A valid token with no claims is still authenticated. |
false |
The request was anonymous (AllowAnonymous), or the route has no authentication method. |
A value sent by the client is always dropped, as with every X-Nocleye-* header, so the backend can trust it. Header rules can’t remove or change it, see header rules.
Removing the credential
Section titled “Removing the credential”By default the credential is forwarded to the backend. RemoveCredentialHeader: true removes it after the token has been validated, so it doesn’t change the authentication result:
Mode |
Header removed |
|---|---|
Bearer, OAuth2, OAuth2Introspection |
Authorization |
RawHeader, JWE |
The header named in HeaderName |
Unlike ForwardAuthorization: false in a header rule, which only knows Authorization, X-Api-Key and X-Auth-Token, this also covers a custom HeaderName. Combine it with ForwardClaims so the backend still knows who the caller is.
Forwarding claims
Section titled “Forwarding claims”ForwardClaims maps a claim name in the token to a header suffix. The backend receives the value in X-Nocleye-Claim-<suffix>:
AuthMethods: corp-sso: Mode: OAuth2 Issuer: https://idp.example.com Algorithms: [RS256] Audience: my-api RemoveCredentialHeader: true ForwardClaims: sub: Sub # X-Nocleye-Claim-Sub tenant: Tenant-Id # X-Nocleye-Claim-Tenant-Id roles: Roles # X-Nocleye-Claim-Roles- Claim headers are namespaced under
X-Nocleye-Claim-, and everyX-Nocleye-*header sent by a client is dropped, so a client can never forge one. - Value format: strings as they are, numbers and booleans in JSON form (
3,true), arrays and objects as compact JSON (["a","b"]). - A claim the token doesn’t have, or whose value can’t be a header value (empty, or with line breaks), is not sent.
- Anonymous requests get no claim headers.
- The suffix must be a valid header name part: letters, digits and
-. No underscores or spaces, and two claims can’t share a suffix (compared ignoring case). See Validation.
Required scopes
Section titled “Required scopes”RequiredScopes lists the scopes a token must hold to reach a route. They are read from the token’s scope claim (space separated) or scp claim (string or array), and all of them are required. Matching is exact. It works with every mode that produces claims: OAuth2, OAuth2Introspection, JWE, Bearer and RawHeader.
Scopes are set on GlobalConfig, a server or a route, not on the authentication method, so the same method can protect many routes with different rules:
AuthMethods: corp-sso: Mode: OAuth2 Issuer: https://idp.example.com Algorithms: [RS256] Audience: my-api RequiredTokenType: at+jwt
ServerConfigs: orders: URL: http://orders:8080 RequiredScopes: [orders] # every route of this server
ServerRoutes: orders-read: TargetServer: orders MatchOptions: {PathPattern: /orders} AuthMethod: corp-sso RequiredScopes: [orders:read] # needs orders AND orders:read orders-write: TargetServer: orders MatchOptions: {PathPattern: /orders/write} AuthMethod: corp-sso RequiredScopes: [orders:write] orders-admin: TargetServer: orders MatchOptions: {PathPattern: /orders/admin} AuthMethod: corp-sso ScopesMode: Override # ignore the server's scopes RequiredScopes: [orders:admin]ScopesMode on a server or a route says how scopes combine across levels:
ScopesMode |
Meaning |
|---|---|
Additive (default) |
The scopes of GlobalConfig, the server and the route are all required. |
Override |
The closest level wins: the scopes of the levels above are ignored. On a route, only the route’s own scopes are required. On a server, the server’s and its routes’ are, but not the global ones. |
Duplicates are ignored. Override on a level with no RequiredScopes of its own removes the inherited scopes without adding any, nocleye check warns about it.
A request with a valid token that lacks a scope gets 403 Forbidden with a header telling the client what is needed, for example WWW-Authenticate: Bearer error="insufficient_scope", scope="orders orders:read". Scopes are checked after the token and before usage control, so a forbidden request doesn’t use up the caller’s quota. The access log and the gw_requests_total metric record these as forbidden, and the access log line has auth_result set to forbidden_scope.
RequiredScopes on a route with no authentication method (neither on the route, its server nor GlobalConfig) is an error, since there would be no token to read them from.
gRPC and WebSocket
Section titled “gRPC and WebSocket”- gRPC: every call is its own request, so authentication, scopes and usage control run on every call, and
X-Nocleye-Authenticatedis sent with each call. A failure is answered as a gRPC status (UNAUTHENTICATED,PERMISSION_DENIED,UNAVAILABLEfor a rate limit,RESOURCE_EXHAUSTEDfor a quota), see Servers and routes. Send the token as gRPC metadata with the name the method reads (authorizationforBearerandOAuth2). - Long streams and WebSocket tunnels are authenticated once, when they open, and
X-Nocleye-Authenticatedis sent with the handshake. A token that is revoked or expires afterwards does not close a stream that is already open. Bound it withMaxLifetimeon the server, set to at most the lifetime of your access tokens, and withIdleTimeout. - Browsers cannot authenticate a WebSocket: the browser API has no way to set headers, and the gateway reads credentials from headers only (
Authorizationor the header named by the method). Native apps, services and command line clients can. Cookies are sent by the browser, but the gateway does not read them as credentials. For a browser route, leave the gateway auth method off, let the backend validate its session cookie, and setAllowedOriginson the server.
Caller identity
Section titled “Caller identity”After a token is validated, the caller is identified by the claim named in IdClaimName. If IdClaimName is not set, or the token doesn’t contain the claim, a fingerprint of the token is used instead. This identity is used as the key for usage control and is written to the access log as caller_id. The backend receives it in X-Nocleye-User-Id.
An anonymous request has no identity: it is limited by its client IP and X-Nocleye-User-Id is not sent.
On routes with an authentication method, the client ID rule is not used.
Validation
Section titled “Validation”- An unknown
ModeorSigningMethodis an error. - For
OAuth2,JWKSUri(when set) must be anhttpsURL, andAlgorithms,IssuerandAudienceare required. WithoutJWKSUri,Issuermust be anhttpsURL.KeyRefandSigningMethodare not used. ADecryptionblock needsKeyRef, both algorithm lists, only supported values, and key management algorithms of one key kind. - For
JWE,KeyRef,HeaderName,KeyManagementAlgandContentEncryptionAlgare required,NestedSigningMethodandNestedKeyRefgo together.SigningMethodis not used. A JWE without a nested signature is a warning. - For
OAuth2Introspection,IntrospectionUrimust be anhttpsURL,ClientSecretRefmust start withenv:orfile:,ClientIdis required (except with thebearerstyle),Audienceis required and the durations must be valid. - A missing
KeyRefis an error inBearerandRawHeadermodes. A missingHeaderNameinRawHeadermode is an error. RequiredScopesentries must be non-empty and contain no spaces,ScopesModemust beAdditiveorOverride, and a route that requires scopes needs an authentication method.ForwardClaimsneeds a non-empty claim name for every entry and a suffix made of letters, digits and-(no underscores or spaces). Two claims mapping to the same suffix, ignoring case, is an error.- Binding an authentication method that does not exist is an error.
- Having no authentication methods at all is a warning: every route is public.
- A method with
AllowAnonymousis a warning, and so is a route that requires scopes while its method allows anonymous callers (they always get403).
