Repository navigation
Conversation
Add jwtBearer as a third OAS-only, Enterprise upstream OAuth grant. The gateway mints an RS256 JWT from the certificate store, exchanges it for an access token, and reuses the existing token cache. Signing failures return 500 without calling the IdP. IdP rejections return 401 or 403; HTTP 400 with invalid_grant is mapped to 401 pending a product decision.
📚 Documentation previewThis PR changes generated documentation (component: cc @TykTechnologies/pms — advisory review requested; this does not block merging. Rendered docs diffdiff -ruN out-base/gateway-config.mdx out-head/gateway-config.mdx
--- out-base/gateway-config.mdx 2026-11-26 19:12:01.649780365 +0000
+++ out-head/gateway-config.mdx 2026-11-26 19:12:03.060488125 +0000
@@ -3157,12 +3157,3 @@
A token with no iss claim is matched by key ID (kid) alone.
It exists for compatibility with legacy records that predate issuer becoming mandatory. Not recommended for production use: without the issuer check, an identity provider that shares signing keys across tenants cannot be distinguished by tenant.
-### allow_unsafe_websocket_origin
-ENV: <b>TYK_GW_ALLOWUNSAFEWEBSOCKETORIGIN</b><br />
-Type: `bool`<br />
-
-AllowUnsafeWebSocketOrigin turns off the Origin check on WebSocket handshakes for GraphQL and Streams APIs, so a handshake from any origin is accepted (default: false).
-It exists for compatibility with browser clients on other origins that connected before the check was added.
-Not recommended: any website can then open a WebSocket to these APIs through a visitor's browser and read the responses.
-To allow a browser client, add its origin to the API's CORS allowed origins instead.
-
diff -ruN out-base/x-tyk-gateway.mdx out-head/x-tyk-gateway.mdx
--- out-base/x-tyk-gateway.mdx 2026-11-26 19:11:55.915403950 +0000
+++ out-head/x-tyk-gateway.mdx 2026-11-26 19:11:55.971746759 +0000
@@ -1133,6 +1133,15 @@
**Field: `password` ([PasswordAuthentication](#passwordauthentication))**
PasswordAuthentication holds the configuration for upstream OAauth password authentication flow.
+**Field: `jwtBearer` ([UpstreamOAuthJWTBearer](#upstreamoauthjwtbearer))**
+JWTBearer holds the configuration for the upstream OAuth2 JWT Bearer grant (RFC 7523).
+Tyk mints a JWT signed with RS256 using the private key of the certificate `certId`,
+exchanges it at `tokenUrl` for an access token and sends that token to the upstream.
+Available only for Tyk OAS APIs.
+
+
+Tyk classic API definition: N/A.
+
### **UpstreamRequestSigning**
UpstreamRequestSigning represents configuration for generating signed requests to an upstream API.
@@ -1747,6 +1756,33 @@
**Field: `extraMetadata` (`[]string`)**
ExtraMetadata holds the keys that we want to extract from the token and pass to the upstream.
+### **UpstreamOAuthJWTBearer**
+
+UpstreamOAuthJWTBearer holds the configuration for the upstream OAuth2 JWT Bearer grant (RFC 7523).
+
+**Field: `header` ([AuthSource](#authsource))**
+Header holds the configuration for the custom header to be used for OAuth authentication.
+
+**Field: `tokenUrl` (`string`)**
+TokenURL is the token endpoint of the authorization server.
+
+**Field: `certId` (`string`)**
+CertID is the ID of the certificate in the Tyk certificate store whose RSA private key
+is used to sign the JWT (RS256).
+
+**Field: `issuer` (`string`)**
+Issuer is the `iss` claim of the JWT (for Salesforce: the Connected App consumer key).
+
+**Field: `subject` (`string`)**
+Subject is the `sub` claim of the JWT (for Salesforce: the username).
+
+**Field: `audience` (`string`)**
+Audience is the `aud` claim of the JWT (for Salesforce: https://login.salesforce.com).
+
+**Field: `expiresIn` ([ReadableDuration](#readableduration))**
+ExpiresIn is the lifetime of the signed JWT, e.g. "2m". Defaults to 2m when unset.
+Some authorization servers cap it (Salesforce requires `exp` within 3 minutes).
+
### **Provider**
Provider defines an issuer to validate and the Client ID to Policy ID mappings.
|
|
This PR introduces the OAuth 2.0 JWT Bearer grant type for upstream authentication, an Enterprise-only feature for OAS APIs. The gateway can now mint an RS256-signed JWT using a private key from the certificate store and exchange it with an Identity Provider (IdP) for an access token. This token is then cached and injected into requests to the upstream service. The implementation is self-contained within the existing upstream OAuth middleware. It adds a new provider for the JWT bearer flow, along with dedicated error handling: signing failures result in an HTTP 500, while IdP rejections are mapped to 401 or 403. Existing client credentials and password grants are unaffected. Files Changed AnalysisThe changes are centered around three main areas:
Architecture & Impact Assessment
JWT Bearer Grant FlowsequenceDiagram
participant Client
participant Tyk Gateway
participant "Identity Provider (IdP)"
participant Upstream Service
Client->>+Tyk Gateway: Request
Tyk Gateway->>Tyk Gateway: Upstream OAuth middleware triggered
alt Token not in cache
Tyk Gateway->>Tyk Gateway: Get private key from Certificate Store
Tyk Gateway->>Tyk Gateway: Create and sign JWT assertion
Tyk Gateway->>+"Identity Provider (IdP)": POST /token (grant_type=jwt-bearer, assertion=JWT)
"Identity Provider (IdP)"-->>-Tyk Gateway: Access Token
Tyk Gateway->>Tyk Gateway: Cache Access Token
end
Tyk Gateway->>+Upstream Service: Request with "Authorization: Bearer <Access Token>"
Upstream Service-->>-Tyk Gateway: Response
Tyk Gateway-->>-Client: Response
Scope Discovery & Context ExpansionThe changes are well-encapsulated within the Enterprise Edition's upstream authentication features. The impact is primarily on developers defining APIs that need to connect to upstreams secured by the JWT Bearer flow.
Metadata
Powered by Visor from Probelabs Last updated: 2026-11-26T19:13:55.907Z | Triggered by: pr_updated | Commit: 7f20aff 💡 TIP: You can chat with Visor using |
|
API Changes --- prev.txt 2026-11-26 19:10:11.360245534 +0000
+++ current.txt 2026-11-26 19:10:06.055155347 +0000
@@ -85,6 +85,9 @@
OAuthAuthorizationTypeClientCredentials = "clientCredentials"
// OAuthAuthorizationTypePassword is the authorization type for password flow.
OAuthAuthorizationTypePassword = "password"
+ // OAuthAuthorizationTypeJWTBearer is the authorization type for the OAuth 2.0 JWT Bearer grant (RFC 7523).
+ // It is available only for Tyk OAS APIs.
+ OAuthAuthorizationTypeJWTBearer = "jwtBearer"
// OAuth2ClientAuthBasic and OAuth2ClientAuthPost are the client authentication
// methods defined by RFC 6749 Section 2.3.1 (the `token_endpoint_auth_method`
@@ -144,6 +147,10 @@
ErrInvalidUpstreamOAuthAuthorizationType = errors.New("invalid OAuth authorization type")
// ErrInvalidUpstreamOAuthClientAuthMethod is the error to return when the configured upstream OAuth client authentication method is invalid.
ErrInvalidUpstreamOAuthClientAuthMethod = errors.New("invalid upstream OAuth client authentication method, valid values are: client_secret_basic, client_secret_post")
+ // ErrUpstreamOAuthJWTBearerOASOnly is the error to return when the JWT Bearer grant is configured on a Tyk classic API.
+ ErrUpstreamOAuthJWTBearerOASOnly = errors.New("upstream OAuth JWT Bearer grant is supported only for Tyk OAS APIs")
+ // ErrInvalidUpstreamOAuthJWTBearerExpiresIn is the error to return when the JWT Bearer expiresIn is not a positive duration.
+ ErrInvalidUpstreamOAuthJWTBearerExpiresIn = errors.New("invalid upstream OAuth JWT Bearer expiresIn, must be a positive duration")
// ErrAllLoadBalancingTargetsZeroWeight is the error to return when all load balancing targets have weight 0.
ErrAllLoadBalancingTargetsZeroWeight = errors.New("all load balancing targets have weight 0, at least one target must have weight > 0")
ErrDNSDiscoveryRequiresLoadBalancing = errors.New("proxy.dns_discovery supplies the target list but does not distribute across it; proxy.enable_load_balancing must be enabled too")
@@ -1689,12 +1696,37 @@
ClientCredentials ClientCredentials `bson:"client_credentials" json:"client_credentials"`
// PasswordAuthentication holds the configuration for upstream OAauth password authentication flow.
PasswordAuthentication PasswordAuthentication `bson:"password,omitempty" json:"password,omitempty"`
+ // JWTBearer holds the configuration for the upstream OAuth2 JWT Bearer grant (RFC 7523).
+ // Supported only for Tyk OAS APIs.
+ JWTBearer UpstreamOAuthJWTBearer `bson:"jwt_bearer,omitempty" json:"jwt_bearer,omitempty"`
}
UpstreamOAuth holds upstream OAuth2 authentication configuration.
func (u UpstreamOAuth) IsEnabled() bool
IsEnabled checks if UpstreamOAuth is enabled for the API.
+type UpstreamOAuthJWTBearer struct {
+ // Header holds the configuration for the custom header to be used for OAuth authentication.
+ Header AuthSource `bson:"header" json:"header"`
+ // TokenURL is the token endpoint of the authorization server.
+ TokenURL string `bson:"token_url" json:"token_url"`
+ // CertID is the ID of the certificate in the Tyk certificate store whose RSA private key signs the JWT.
+ CertID string `bson:"cert_id" json:"cert_id"`
+ // Issuer is the `iss` claim of the JWT.
+ Issuer string `bson:"issuer" json:"issuer"`
+ // Subject is the `sub` claim of the JWT.
+ Subject string `bson:"subject" json:"subject"`
+ // Audience is the `aud` claim of the JWT.
+ Audience string `bson:"audience" json:"audience"`
+ // ExpiresIn is the lifetime of the signed JWT (`exp` = now + ExpiresIn).
+ // When zero/unset, the gateway uses a 2 minute default.
+ ExpiresIn tyktime.ReadableDuration `bson:"expires_in,omitempty" json:"expires_in,omitempty"`
+}
+ UpstreamOAuthJWTBearer holds the configuration for the upstream OAuth2 JWT
+ Bearer grant (RFC 7523). Tyk mints a JWT signed (RS256) with the private key
+ of the certificate CertID, and exchanges it at TokenURL for an access token
+ that is then sent to the upstream.
+
type UptimeTests struct {
// Disabled indicates whether the uptime test configuration is disabled.
Disabled bool `bson:"disabled" json:"disabled"`
@@ -6621,6 +6653,13 @@
ClientCredentials *ClientCredentials `bson:"clientCredentials,omitempty" json:"clientCredentials,omitempty"`
// PasswordAuthentication holds the configuration for upstream OAauth password authentication flow.
PasswordAuthentication *PasswordAuthentication `bson:"password,omitempty" json:"password,omitempty"`
+ // JWTBearer holds the configuration for the upstream OAuth2 JWT Bearer grant (RFC 7523).
+ // Tyk mints a JWT signed with RS256 using the private key of the certificate `certId`,
+ // exchanges it at `tokenUrl` for an access token and sends that token to the upstream.
+ // Available only for Tyk OAS APIs.
+ //
+ // Tyk classic API definition: N/A.
+ JWTBearer *UpstreamOAuthJWTBearer `bson:"jwtBearer,omitempty" json:"jwtBearer,omitempty"`
}
UpstreamOAuth holds the configuration for OAuth2 Client Credentials flow.
@@ -6628,6 +6667,34 @@
func (u *UpstreamOAuth) Fill(api apidef.UpstreamOAuth)
+type UpstreamOAuthJWTBearer struct {
+ // Header holds the configuration for the custom header to be used for OAuth authentication.
+ Header *AuthSource `bson:"header,omitempty" json:"header,omitempty"`
+ // TokenURL is the token endpoint of the authorization server.
+ TokenURL string `bson:"tokenUrl" json:"tokenUrl"`
+ // CertID is the ID of the certificate in the Tyk certificate store whose RSA private key
+ // is used to sign the JWT (RS256).
+ CertID string `bson:"certId" json:"certId"`
+ // Issuer is the `iss` claim of the JWT (for Salesforce: the Connected App consumer key).
+ Issuer string `bson:"issuer" json:"issuer"`
+ // Subject is the `sub` claim of the JWT (for Salesforce: the username).
+ Subject string `bson:"subject" json:"subject"`
+ // Audience is the `aud` claim of the JWT (for Salesforce: https://login.salesforce.com).
+ Audience string `bson:"audience" json:"audience"`
+ // ExpiresIn is the lifetime of the signed JWT, e.g. "2m". Defaults to 2m when unset.
+ // Some authorization servers cap it (Salesforce requires `exp` within 3 minutes).
+ ExpiresIn ReadableDuration `bson:"expiresIn,omitempty" json:"expiresIn,omitempty"`
+}
+ UpstreamOAuthJWTBearer holds the configuration for the upstream OAuth2 JWT
+ Bearer grant (RFC 7523).
+
+func (j *UpstreamOAuthJWTBearer) ExtractTo(api *apidef.UpstreamOAuthJWTBearer)
+ ExtractTo extracts *UpstreamOAuthJWTBearer into
+ *apidef.UpstreamOAuthJWTBearer.
+
+func (j *UpstreamOAuthJWTBearer) Fill(api apidef.UpstreamOAuthJWTBearer)
+ Fill fills *UpstreamOAuthJWTBearer from apidef.UpstreamOAuthJWTBearer.
+
type UpstreamRequestSigning struct {
// Enabled determines if request signing is enabled or disabled.
Enabled bool `bson:"enabled" json:"enabled"` // required
@@ -8304,12 +8371,6 @@
// A token with no iss claim is matched by key ID (kid) alone.
// It exists for compatibility with legacy records that predate issuer becoming mandatory. Not recommended for production use: without the issuer check, an identity provider that shares signing keys across tenants cannot be distinguished by tenant.
AllowUnsafeIDPMissingIssuer bool `json:"allow_unsafe_idp_missing_issuer"`
-
- // AllowUnsafeWebSocketOrigin turns off the Origin check on WebSocket handshakes for GraphQL and Streams APIs, so a handshake from any origin is accepted (default: false).
- // It exists for compatibility with browser clients on other origins that connected before the check was added.
- // Not recommended: any website can then open a WebSocket to these APIs through a visitor's browser and read the responses.
- // To allow a browser client, add its origin to the API's CORS allowed origins instead.
- AllowUnsafeWebSocketOrigin bool `json:"allow_unsafe_websocket_origin"`
}
Config is the configuration object used by Tyk to set up various parameters.
@@ -10596,12 +10657,6 @@
OAS oas.OAS
StripListenPath model.StripListenPathFunc
-
- // WebSocketOriginAllowed reports whether a WebSocket handshake may
- // proceed. Bento's http_server output accepts every origin unless its own
- // cors setting is on, so the Gateway checks the origin first. When nil,
- // handshakes are refused.
- WebSocketOriginAllowed func(*http.Request) bool
}
APISpec is a subset of gateway.APISpec for the values the middleware
consumes.
@@ -10828,6 +10883,7 @@
ClientCredentialsAuthorizeType = "clientCredentials"
PasswordAuthorizeType = "password"
+ JWTBearerAuthorizeType = "jwtBearer"
)
VARIABLES
@@ -10848,6 +10904,9 @@
type BaseMiddleware interface {
model.LoggerProvider
FireEvent(name apidef.TykEvent, meta interface{})
+ // GetClientCertificate returns the certificate (with private key) stored
+ // under certID in the gateway certificate store.
+ GetClientCertificate(certID string) (*tls.Certificate, error)
}
BaseMiddleware is the subset of BaseMiddleware APIs that the middleware
uses.
@@ -10881,6 +10940,50 @@
}
Gateway is the subset of Gateway APIs that the middleware uses.
+type JWTBearerClient struct {
+ // Has unexported fields.
+}
+ JWTBearerClient obtains and caches access tokens using the JWT Bearer grant.
+
+func (client *JWTBearerClient) GetToken(r *http.Request) (string, error)
+ GetToken returns the access token from cache, or obtains a new one.
+
+func (client *JWTBearerClient) ObtainToken(ctx context.Context) (*oauth2.Token, error)
+ ObtainToken signs a JWT assertion and exchanges it at the token endpoint.
+ The token endpoint is not called when the assertion cannot be signed.
+
+type JWTBearerIdPError struct {
+ // IdPStatus is the HTTP status returned by the token endpoint.
+ IdPStatus int
+ // IdPError is the OAuth `error` code returned by the token endpoint.
+ IdPError string
+ // Description is the OAuth `error_description` (or a truncated raw body).
+ Description string
+ // StatusCode is the HTTP status the gateway responds with.
+ StatusCode int
+}
+ JWTBearerIdPError is returned when the token endpoint rejects the assertion
+ or answers with an unusable response. StatusCode is the HTTP status the
+ gateway returns to the client (401 or 403).
+
+func (e *JWTBearerIdPError) Error() string
+
+type JWTBearerOAuthProvider struct{}
+ JWTBearerOAuthProvider implements the OAuth 2.0 JWT Bearer grant (RFC 7523
+ §2.1).
+
+type JWTBearerSigningError struct {
+ CertID string
+ Err error
+}
+ JWTBearerSigningError is returned when the JWT assertion cannot be built:
+ the certificate is missing, has no (RSA) private key, or signing fails.
+ It maps to HTTP 500 and the IdP is never called.
+
+func (e *JWTBearerSigningError) Error() string
+
+func (e *JWTBearerSigningError) Unwrap() error
+
type Middleware struct {
Spec model.MergedAPI
Gw Gateway
@@ -10891,7 +10994,7 @@
}
Middleware implements upstream OAuth middleware.
-func NewMiddleware(gw Gateway, mw BaseMiddleware, spec model.MergedAPI, ccStorageHandler Storage, pwStorageHandler Storage) *Middleware
+func NewMiddleware(gw Gateway, mw BaseMiddleware, spec model.MergedAPI, ccStorageHandler, pwStorageHandler, jwtStorageHandler Storage) *Middleware
NewMiddleware returns a new instance of Middleware.
func (m *Middleware) EnabledForSpec() bool
@@ -10949,6 +11052,9 @@
GetKey(key string) (string, error)
SetKey(string, string, int64) error
Lock(key string, timeout time.Duration) (bool, error)
+ // DeleteRawKey removes a key without applying the storage prefix. It releases
+ // the token lock, which Lock also stores unprefixed.
+ DeleteRawKey(key string) bool
}
Type Storage is a subset of storage.RedisCluster
@@ -11752,8 +11858,7 @@
func (t *BaseMiddleware) CheckSessionAndIdentityForValidKey(originalKey string, r *http.Request) (user.SessionState, bool)
CheckSessionAndIdentityForValidKey will check first the Session store for a
valid key, if not found, it will try the Auth Handler, if not found it will
- fail. A JWT claims-only session is never valid here: only the JWT middleware
- may use it, after the token's claims passed validation.
+ fail
func (t *BaseMiddleware) Config() (interface{}, error)
|
✅ Security Check PassedNo security issues found – changes LGTM. ✅ Security Check PassedNo security issues found – changes LGTM. \n\nArchitecture Issues (1)
✅ Performance Check PassedNo performance issues found – changes LGTM. ✅ Quality Check PassedNo quality issues found – changes LGTM. Powered by Visor from Probelabs Last updated: 2026-11-26T19:13:17.027Z | Triggered by: pr_updated | Commit: 7f20aff 💡 TIP: You can chat with Visor using |
schema-gen lint requires symbol comments to end with a period.
Address the Quality Gate failure (Reliability Rating on New Code was C): check ignored errors in test helpers, put error last in processAndFill, group NewMiddleware Storage params, and reword the invalid_grant comment so it is not a TODO.
Use a 15s-timeout HTTP client when no external-services OAuth client is configured, so an unresponsive token endpoint cannot hang the request.
Length-prefix each field before hashing so values containing '|' cannot make two different grant configs share a cached access token.
- Set IsOAS before validation on the Gateway's OAS and MCP create/update endpoints, so the OAS-only rule no longer rejects jwtBearer there. - Release the token fetch lock after fetching. After an IdP rejection the lock stayed held for 5s and other requests got a 500 instead of 401/403. This also applies to the client credentials and password grants. - Return a generic "upstream authentication failed" message to the API consumer; the IdP error description and certificate ID are only logged and sent with the UpstreamOAuthError event. - Refuse the grant at runtime for classic APIs that bypassed save-time validation (e.g. loaded from disk).
🎯 Recommended Merge TargetsBased on JIRA ticket TT-16926: OAuth 2.0 JWT Bearer Flow for Upstream Authentication Fix Version: Tyk 5.17.0
Required:
📋 Workflow
|
Selecting jwtBearer without a jwtBearer block passed both the schema and the validator, and every request then failed with a 500. The validator now rejects it on save unless tokenUrl, certId, issuer, subject and audience are all set.
|
SentinelOne CNS Hardcoded Secret Detector SentinelOne CNS is a cloud-agnostic, agentless CSPM & CWPP solution that continuously detects and prevents vulnerabilities that have the highest probability of being exploited in Azure, AWS, Google Cloud, and Kubernetes. |
|



Description
Adds
jwtBeareras a third grant type under existing upstream OAuth (x-tyk-api-gateway.upstream.authentication.oauth). OAS and Enterprise only.The gateway mints an RS256 JWT from a private key in the certificate store (
iss,sub,aud,iat,exp,jti), exchanges it at the configured token URL withgrant_type=urn:ietf:params:oauth:grant-type:jwt-bearerandassertion, and reuses the existing access-token cache and upstream header injection.Signing or certificate failures return HTTP 500 and do not call the IdP or the upstream. IdP rejections return 401 or 403 and are not cached. Classic APIs cannot enable the grant. Existing client credentials and password grants are unchanged.
Docs and Dashboard API Designer work are not in this PR.
Related Issue
https://tyktech.atlassian.net/browse/TT-16926
Motivation and Context
Odido needs Tyk to authenticate to Salesforce with the OAuth 2.0 JWT Bearer flow (RFC 7523). Upstream OAuth already supports client credentials and password grants; this adds the missing grant.
How This Has Been Tested
go test ./apidef/...go test -tags ee -count=1 ./ee/middleware/upstreamoauth/(mock IdP that verifies the JWT; cache reuse/renewal; missing key → 500 with no IdP call; IdP rejection → 401/403)go test -tags ee -count=1 -run 'TestUpstreamOAuthJWTBearer' ./gateway/(real certificate store and Redis)OSS and EE gateway binaries compile.
go build ./...still fails on the pre-existingtest/gopluginspackage mainfixture; not caused by this change.Screenshots (if appropriate)
Types of changes
Checklist
Documentation will follow in a separate PR. This change does not update go.mod and does not request a coverage exception.
Open product questions (provisional in this PR)
invalid_grantis mapped to 401 (TODO in code).expires_in, the access token is cached for 5 minutes.kid,x5t#S256, orclient_idon the token request.Ticket Details
TT-16926
Generated at: 2026-11-26 19:11:37