title | subtitle | description |
---|---|---|
JWT Authentication in the GraphOS Router |
Restrict access to credentialed users and systems |
Protect sensitive data by enabling JWT authentication in the Apollo GraphOS Router. Restrict access to credentialed users and systems. |
Authentication is crucial to prevent illegitimate access and protect sensitive data in your graph. The GraphOS Router supports request authentication and key rotation via the JSON Web Token (JWT) and JSON Web Key (JWK) standards. This support is compatible with popular identity providers (IdPs) like Okta and Auth0.
By enabling JWT authentication, you can block malicious traffic at the edge of your graph instead of relying on header forwarding to propagate tokens to your subgraphs.
Your subgraphs should always be accessible only via the router—not directly by clients. This is especially true if you rely on JWT authentication in the router. See Securing your subgraphs for steps to restrict subgraph access to only your router.
These are the high-level steps of JWT-based authentication with the GraphOS Router:
-
Whenever a client authenticates with your system, your IdP issues that client a valid JSON Web Token (JWT).
-
In its subsequent requests to your router, the authenticated client provides its JWT in a designated HTTP header.
-
Whenever your router receives a client request, it extracts the JWT from the designated header (if present).
- If no JWT is present, the request proceeds. You can reject requests with no accompanying JWT at a later phase (see below).
-
Your router validates the extracted JWT using a corresponding JSON Web Key (JWK).
- Your router obtains all of its known JWKs from URLs that you specify in its configuration file. Each URL provides its keys within a single JSON object called a JWK Set (or a JWKS).
- If validation fails, the router rejects the request. This can occur if the JWT is malformed, or if it's been expired for more than 60 seconds (this window accounts for synchronization issues).
-
The router extracts all claims from the validated JWT and includes them in the request's context (
apollo::authentication::jwt_claims
), making them available to your router customizations, such as Rhai scripts. -
The router will insert the status of JWT processing into the request context (
apollo::authentication::jwt_status
). This status is informational and may be used for logging or debugging purposes. -
Your customizations can handle the request differently depending on the details of the extracted claims, and/or you can propagate the claims to subgraphs to enable more granular access control.
- For examples, see below.
If you use your own custom IdP, advanced configuration is required.
Otherwise, if you issue JWTs via a popular third-party IdP (Auth0, Okta, PingOne, etc.), enabling JWT authentication in your router is a two step process described below.
-
Set configuration options for JWT authentication in your router's YAML config file, under the
authentication
key:authentication: router: jwt: jwks: # This key is required. - url: https://dev-zzp5enui.us.auth0.com/.well-known/jwks.json issuer: <optional name of issuer> poll_interval: <optional poll interval> headers: # optional list of static headers added to the HTTP request to the JWKS URL - name: User-Agent value: router # These keys are optional. Default values are shown. header_name: Authorization header_value_prefix: Bearer on_error: Error # array of alternative token sources sources: - type: header name: X-Authorization value_prefix: Bearer - type: cookie name: authz
These options are documented below.
-
Pass all of the following to the
router
executable on startup:- The path to the router's YAML configuration file (via the
--config
option) - The graph ref for the GraphOS variant your router should use (via the
APOLLO_GRAPH_REF
environment variable) - A graph API key that enables the router to authenticate with GraphOS to fetch its supergraph schema (via the
APOLLO_KEY
environment variable)
APOLLO_GRAPH_REF=docs-example-graph@main APOLLO_KEY="..." ./router --config router.yaml
- The path to the router's YAML configuration file (via the
When the router starts up, it displays a log message that confirms which jwks
are in use:
2023-02-03T14:05:28.018932Z INFO JWT authentication using JWKSets from jwks=[{ url: "file:///router/jwks.json" }]
The following configuration options are supported:
Option | Description | |
---|---|---|
Required. A list of JWK Set (JWKS) configuration options:
|
||
The name of the HTTP header that client requests will use to provide their JWT to the router. Must be a valid name for an HTTP header. The default value is |
||
The string that will always precede the JWT in the header value corresponding to The default value is |
||
This setting controls the behavior of the router when an error occurs during JWT validation. Possible values are
Regardless of whether JWT authentication succeeds, the status of JWT processing is inserted into the request context ( // On failure
{
// Whether the JWT came from a header or cookie source
type: string,
// The name of the source's field
name: string,
// Error details
error: {
// A user-friendly error message
message: string,
// A machine-readable error code
code: string,
// The underlying reason for the error, if any
reason: string?
}
}
// On success
{
// Whether the JWT came from a header or cookie source
type: string,
// The name of the source's field
name: string
} |
This is an array of possible token sources, as it could be provided in different headers depending on the client, or it could be stored in a cookie. If the default token source defined by the above authentication:
router:
jwt:
jwks:
- url: https://dev-zzp5enui.us.auth0.com/.well-known/jwks.json
sources:
- type: header
name: X-Authorization
value_prefix: Bearer
- type: cookie
name: authz |
|
This option lets you have a mix of By default, the router responds with an error when it encounters an unknown prefix in the When If you set If you set The default value is |
After the GraphOS Router validates a client request's JWT, it adds that token's claims to the request's context at this key: apollo::authentication::jwt_claims
- If no JWT is present for a client request, this context value is the empty tuple,
()
.- If a JWT is present but validation of the JWT fails,
- When
on_error
is set toError
, the router rejects the request.- When
on_error
is set toContinue
, the router continues processing the request, and the context value is the empty tuple,()
.
If unauthenticated requests should be rejected, the router can be configured like this:
authorization:
require_authentication: true
Claims are the individual details of a JWT's scope. They might include details like the ID of the associated user, any roles assigned to that user, and the JWT's expiration time. See the spec.
Because claims are added to the context, you can define custom logic for handling each request based on the details of its claims. You can define this logic within a Rhai script or external coprocessor at the supergraph service level (for more on these options, see Router Customizations).
Below are 2 example Rhai script customizations that demonstrate actions the router can perform based on a request's claims.
Below is an example Rhai script that forwards a JWT's claims to individual subgraphs via HTTP headers (one header for each claim). This enables each subgraph to define logic to handle (or potentially reject) incoming requests based on claim details. This function should be imported and run in your main.rhai
file.
This script should be run in the router's SubgraphService
, which executes before the router sends a subquery to an individual subgraph. Learn more about router services.
fn process_request(request) {
let claims = request.context[Router.APOLLO_AUTHENTICATION_JWT_CLAIMS];
if claims ==() {
throw #{
status: 401
};
}
// Add each claim key-value pair as a separate HTTP header.
// Note that that claims that are not present in the JWT will be added as empty strings.
let claim_names = ["claim_1", "claim_2", "claim_3"];
for claim_name in claim_names {
let claim = claims[claim_name];
claim = if claim == () {""} else {claim};
request.subgraph.headers[claim_name] = claim;
}
}
Explicitly listing claims and always setting headers for them is strongly recommended to avoid possible security issues when forwarding headers to subgraphs.
Below is an example Rhai script that forwards a JWT's claims to individual subgraphs via GraphQL extension. This enables each subgraph to define logic to handle (or potentially reject) incoming requests based on claim details. This function should be imported and run in your main.rhai
file.
This script should be run in the router's SubgraphService
, which executes before the router sends a subquery to an individual subgraph. Learn more about router services.
fn process_request(request) {
let claims = request.context[Router.APOLLO_AUTHENTICATION_JWT_CLAIMS];
if claims ==() {
throw #{
status: 401
};
}
request.subgraph.body.extensions["claims"] = claims;
}
Below is an example Rhai script that throws distinct errors for different invalid JWT claim details. This function should be imported and run in your main.rhai
file.
This script should be run in the router's SupergraphService
, which executes before the router begins generating the query plan for an operation. Learn more about router services.
fn process_request(request) {
// Router.APOLLO_AUTHENTICATION_JWT_CLAIMS is a Rhai-scope
// constant with value `apollo::authentication::jwt_claims`
let claims = request.context[Router.APOLLO_AUTHENTICATION_JWT_CLAIMS];
if claims == () || !claims.contains("iss") || claims["iss"] != "https://idp.local" {
throw #{
status: 401,
message: "Unauthorized"
};
}
// Happy path: We have valid claims from the correct idP.
}
In order to use the above Rhai examples, you must import them into your main.rhai
like this:
import "claims_validation" as claims_validation;
import "claims_forwarding" as claims_forwarding;
fn supergraph_service(service) {
let request_callback = |request| {
claims_validation::process_request(request);
};
service.map_request(request_callback);
}
fn subgraph_service(service, subgraph) {
let request_callback = |request| {
claims_forwarding::process_request(request);
};
service.map_request(request_callback);
}
You may require information beyond what your JSON web tokens provide. For example, a token's claims may include user IDs, which you then use to look up user roles. For situations like this, you can augment the claims from your JSON web tokens with coprocessors.
A RouterService
coprocessor is appropriate for augmenting claims since the router calls it directly after receiving a client request. The router calls it after the JWT authentication plugin, so you can use a RouterService
coprocessor to:
- receive the list of claims extracted from the JWT
- use information like the
sub
(subject) claim to look up the user in an external database or service - insert additional data in the claims list
- return the claims list to the router
For example, if you use this router configuration:
authentication:
router:
jwt:
jwks:
- url: "file:///etc/router/jwks.json"
coprocessor:
url: http://127.0.0.1:8081
router:
request:
context: true
The router sends requests to the coprocessor with this format:
{
"version": 1,
"stage": "RouterRequest",
"control": "continue",
"id": "d0a8245df0efe8aa38a80dba1147fb2e",
"context": {
"entries": {
"apollo::authentication::jwt_claims": {
"exp": 10000000000,
"sub": "457f6bb6-789c-4e8b-8560-f3943a09e72a"
}
}
},
"method": "POST"
}
The coprocessor can then look up the user with the identifier specified in the sub
claim and return a response with more claims:
{
"version": 1,
"stage": "RouterRequest",
"control": "continue",
"id": "d0a8245df0efe8aa38a80dba1147fb2e",
"context": {
"entries": {
"apollo::authentication::jwt_claims": {
"exp": 10000000000,
"sub": "457f6bb6-789c-4e8b-8560-f3943a09e72a",
"scope": "profile:read profile:write"
}
}
}
}
For more information, refer to the coprocessor documentation.
- Most third-party IdP services create and host a JSON Web Key Set (JWKS) for you. Read this section only if you use a custom IdP that doesn't publish its JWKS at a router-accessible URL.
- To be compatible with JWT authentication supported by GraphOS Router, your IdP (or whatever service issues JWTs to authenticated clients) must use one of the signature algorithms supported by the router.
The GraphOS Router obtains each JSON Web Key (JWK) that it uses from the URLs that you specify via the jwks
configuration option. Each URL must provide a set of valid JWKs in a single JSON object called a JWK Set (or JWKS).
Consult your IdP's documentation to obtain the JWKS URL to pass to your router.
To provide a JWKS to your router, configure your IdP service to do the following whenever its collection of valid JWKs changes (such as when a JWK expires or is rotated):
- Generate a valid JWKS object that includes the details of every JWK that the router requires to perform token validation.
- Write the JWKS object to a location that your router can reach via a
file://
orhttps://
URL.⚠️ If any of your JWKs uses a symmetric signature algorithm (such asHS256
), always use afile://
URL. Symmetric signature algorithms use a shared key that should never be accessible over the network.
Make sure the IdP is configured to perform these steps every time its collection of JWKs changes.
A JWKS is a JSON object with a single top-level property: keys
. The value of keys
is an array of objects that each represent a single JWK:
{
"keys": [
{
// These JWK properties are explained below.
"kty": "RSA",
"alg": "RS256",
"kid": "abc123",
"use": "sig",
"n": "0vx7agoebGcQSuu...",
"e": "AQAB"
}
]
}
It's common for the keys
array to contain only a single JWK, or sometimes two if your IdP is in the process of rotating a key.
JWK object properties fall into two categories:
- Universal properties. You include these in your JWK objects regardless of which signature algorithm you use.
- Algorithm-specific properties. You include these only for JWK objects that use a corresponding signature algorithm.
These properties apply to any JWK:
Option | Description |
---|---|
Short for key type. The high-level type of cryptographic algorithm that the JWK uses (such as |
|
Short for algorithm. The exact cryptographic algorithm to use with the JWK, including key size (such as |
|
Short for key identifier. The JWK's unique identifier. Your IdP should generate each JWK's JWTs created with a particular key can include that key's identifier in their payload, which helps the router determine which JWK to use for validation. |
|
Indicates how a JWK is used. Spec-defined values are For keys you're using to perform JWT authentication, this value should be |
See also the JWA spec.
{
// Universal properties
"kty": "RSA",
"alg": "RS256",
"kid": "abc123",
// highlight-start
// Algorithm-specific properties
"n": "0vx7agoebGcQSuu...", // Shortened for readability
"e": "AQAB"
// highlight-end
}
Option | Description |
---|---|
The RSA public key's modulus value, as the base64-encoded value of the unsigned integer. |
|
The RSA public key's exponent value, as the base64-encoded value of the unsigned integer. This value is often |
See also the JWA spec.
{
// Universal properties
"kty": "EC",
"alg": "ES256",
"kid": "afda85e09a320cf748177874592de64d",
"use": "sig",
// highlight-start
// Algorithm-specific properties
"crv": "P-256",
"x": "opFUViwCYVZLmsbG2cJTA9uPvOF5Gg8W7uNhrcorGhI",
"y": "bPxvCFKmlqTdEFc34OekvpviUUyelGrbi020dlgIsqo"
// highlight-end
}
Option | Description |
---|---|
Indicates which cryptographic curve is used with this public key. Spec-defined curves include:
|
|
The x-coordinate of the elliptic curve point for this public key, as the base64-encoded value of the coordinate's octet string representation. |
|
The y-coordinate of the elliptic curve point for this public key, as the base64-encoded value of the coordinate's octet string representation. |
{
// Universal properties
"kty": "oct",
"alg": "HS256",
"kid": "key1",
"use": "sig",
// highlight-start
// Symmetric-algorithm-specific property
"k": "c2VjcmV0Cg" // ⚠️ This is a base64-encoded shared secret! ⚠️
// highlight-end
}
Option | Description |
---|---|
The value of the shared symmetric key, as the (URL safe, without padding) base64-encoded value of the key's octet sequence representation.
|
To match an incoming JWT with its corresponding JWK, the router proceeds through descending "specificity levels" of match criteria until it identifies the first compatible JWK from its JWK Sets:
- The JWT and JWK match both
kid
andalg
exactly. - The JWT and JWK match
kid
, and the JWT'salg
is compatible with the JWK'skty
. - The JWT and JWK match
alg
exactly. - The JWT's
alg
is compatible with the JWK'skty
.
This matching strategy is necessary because some identity providers (IdPs) don't specify alg
or kid
values in their JWKS. However, they always specify a kty
, because that value is required by the JWK specification.
Because the GraphOS Router handles validating incoming JWTs, you rarely need to pass those JWTs to individual subgraphs in their entirety. Instead, you usually want to pass JWT claims to subgraphs to enable fine-grained access control.
If you do need to pass entire JWTs to subgraphs, you can do so via the GraphOS Router's general-purpose HTTP header propagation settings.
If your router enables tracing, the JWT authentication plugin has its own tracing span: authentication_plugin
If your router exports metrics, the JWT authentication plugin exports the apollo.router.operations.authentication.jwt
metric. You can use the metric's authentication.jwt.failed
attribute to count failed authentications. If the authentication.jwt.failed
attribute is absent or false
, the authentication succeeded.
You can use the Apollo Solutions router JWKS generator to create a router configuration file for use with the authentication plugin.