Token Hook

A token hook runs a Management Flow every time the token endpoint is about to issue an access token for an Inbound App. The flow receives the details of the token request, and its output can add claims to the access token, remove claims from it, or reject the request.

This page is for developers who need per-request logic on machine and delegated tokens. If you only need the same extra claims on every token, a JWT template is simpler and does not add a flow run to each request.

Availability

Descope enables the token hook per project. Contact Descope to turn it on for your project. Until it is on, saving token hook settings on an Inbound App fails.

Why Use a Token Hook

A JWT template decides the shape of a token ahead of time. Backends and agents get tokens with grants such as client credentials, token exchange, and JWT bearer. These grants run no user-facing flow, so there is no place to look at the request and decide what the token should say.

The token hook gives you that place. Your flow can look up the calling workload in your own system with a connector and add an entitlement claim that depends on the requested resource. The flow can also drop a claim that a downstream API must not see, or refuse a token to a client that your system blocked. Descope still validates the grant, the client, and the scopes first. The flow only decides what to add to or remove from a token that Descope would otherwise issue.

How It Works

The token endpoint runs the hook only for the grants you select on the app. Each request goes through these steps:

  1. Descope validates the token request as usual: the client authentication, the grant, the scopes, and the consent.
  2. Descope runs the app's Management Flow with the request details as input, and waits up to the configured timeout.
  3. The flow ends with an End action whose output says whether to reject the request and which claims to add or remove.
  4. Descope applies the output and issues the access token, or returns an OAuth error when the flow rejected the request.

The hook runs on four grants: client_credentials, token_exchange, jwt_bearer, and refresh_token. The authorization code, device code, and CIBA grants never run the hook, because they already run a user flow where you can shape the session. Descope also never runs the hook when it issues or accepts an ID-JAG, because the specification defines those claims.

Configuring the Token Hook

You first need a Management Flow for the hook to run. Create one from the Flows page, as described in Creating Management Flows. The flow has to be enabled and in the same project as the Inbound App.

In the Console

Open the app on the Inbound Apps page, go to the Grant Types tab, and find the Token Hook section. Select a Management Flow to show the other settings:

  • Management Flow: The flow to run. Select None to remove the hook from the app.
  • Grants: The grants that run the hook. Select at least one of client credentials, token exchange, JWT bearer, and refresh token.
  • Timeout (ms): How long the token request waits for the flow. Leave it empty to use the default of 2000. The maximum is 5000.
  • Fail Open: What happens when the flow fails or times out. When it is off, the token request fails. When it is on, Descope issues the token without the hook's changes. See Failures.

With the Management API

You can also set the hook with the tokenHookSettings field when you create, update, or patch an Inbound App with the Management API. The patch endpoint changes only the fields you send, so it is the safest way to add a hook to an existing app:

curl -X POST "__BaseURL__/v1/mgmt/thirdparty/app/patch" \
  -H "Authorization: Bearer __ProjectID__:<MANAGEMENT_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "<APP_ID>",
    "tokenHookSettings": {
      "flowId": "<MANAGEMENT_FLOW_ID>",
      "grants": ["client_credentials", "token_exchange"],
      "timeoutMs": 2000,
      "failOpen": false
    }
  }'

The tokenHookSettings object has the following fields:

FieldTypeDescription
flowIdstringThe ID of the Management Flow to run. An empty string removes the hook.
grantsstring arrayThe grants that run the hook: client_credentials, token_exchange, jwt_bearer, and refresh_token. At least one is required when flowId is set.
timeoutMsintegerHow long the token request waits for the flow, in milliseconds. 0 means the default of 2000. The maximum is 5000.
failOpenbooleanWhen true, Descope issues the token without the hook's changes if the flow fails or times out. Defaults to false, which fails the token request.

A patch request without tokenHookSettings keeps the hook the app already has. To remove the hook, send tokenHookSettings with an empty flowId. Descope rejects the save when the flow does not exist, is not enabled, or is not a Management Flow.

Flow Input

Descope passes the token request to the flow as input. Inside the flow, each input key is available in the flow context as client.<key>, the same as for any Management Flow input. For example, the grant type is client.grantType and the user's ID is client.user.userId.

The input has the following keys. Descope leaves out a key that has no value for the request.

KeyDescription
grantTypeThe grant of the token request: client_credentials, urn:ietf:params:oauth:grant-type:token-exchange, urn:ietf:params:oauth:grant-type:jwt-bearer, or refresh_token.
inboundAppIdThe ID of the Inbound App.
appThe Inbound App, with its id, clientId, and customAttributes (the app's custom attributes).
userThe user the token is for, with userId, loginIds, customAttributes, roles, permissions, and tenants (a list of tenantId, roles, and permissions). An app token, such as a client credentials token, has no user.
tenantThe tenant the token is issued for.
scopesThe scopes the token will carry.
resourceThe requested Resource.
audienceThe audience of the token.
assertionClaimsJWT bearer: the claims of the assertion, after Descope validated its signature.
subjectTokenClaimsToken exchange: the claims of the subject token, after Descope validated it.
clientAssertionClaimsThe claims of the client assertion that the client authenticated with, when it uses Private Key JWT or Workload Identity Federation. Present on every grant that runs the hook.
actorToken exchange with delegation: the actor of the exchange.
carriedClaimsRefresh: the custom claims the refresh token carries.

For example, a client credentials request from an app that authenticates with a client secret gives the flow this input:

{
  "grantType": "client_credentials",
  "inboundAppId": "<APP_ID>",
  "app": {
    "id": "<APP_ID>",
    "clientId": "<CLIENT_ID>",
    "customAttributes": { "partnerTier": "gold" }
  },
  "scopes": ["orders:read"],
  "resource": "https://api.example.com",
  "audience": "https://api.example.com"
}

Flow Output

The flow returns its decision with the Flow output of its End action. Descope reads these keys and ignores any other key:

KeyTypeDescription
rejectbooleanWhen true, Descope rejects the token request.
errorstringThe OAuth error for a rejection: access_denied (the default) or invalid_grant. Any other value falls back to access_denied.
errorDescriptionstringThe error_description that the client receives for a rejection. Descope keeps printable ASCII characters only, up to 256 characters.
claimsobjectClaims to add to the access token, at the top level of the token.
removeClaimsstring arrayNames of claims to remove from the access token.

An End action with no output, or an output with none of these keys, issues the token unchanged.

Adding Claims

The claims object adds each key as a top-level claim of the access token. A hook claim takes precedence over a claim of the same name from the JWT template:

{
  "claims": {
    "partner_tier": "gold",
    "entitlements": ["orders", "invoices"]
  }
}

Removing Claims

The removeClaims list removes claims by name, for example a claim that the JWT template adds but that one Resource must not receive:

{
  "removeClaims": ["internal_account_id"]
}

You can return claims and removeClaims together in one output.

Rejecting the Request

When reject is true, Descope fails the token request with HTTP 400 and does not issue or rotate any token. A rejection always applies, even on an app with Fail Open turned on, and Descope ignores claims and removeClaims in the same output:

{
  "reject": true,
  "error": "invalid_grant",
  "errorDescription": "This workload is suspended"
}

The client receives a standard OAuth error response:

{
  "error": "invalid_grant",
  "error_description": "This workload is suspended"
}

Without error, the response uses access_denied. Without errorDescription, the response uses The token request was rejected.

Reserved Claims and Limits

The hook cannot set or remove the claims that Descope computes for every token. These include sub, iss, aud, exp, iat, nbf, jti, scope, client_id, cnf, amr, acr, tenants, roles, permissions, dct, dci, txn, su, authorization_details, and other Descope system claims. To control those values, use the Inbound App settings, the scopes, and the policies for the app instead.

The hook's claims also follow these limits:

  • Claim names: The maximum length of a claim name and the maximum number of added claims are the same as for the project's custom claims.
  • Total size: The added and removed claims together must fit in 4 KiB of JSON.

When the output breaks one of these rules, Descope fails the token request with HTTP 500 server_error. Fail Open does not apply here, because a reserved or oversized claim is a mistake in the flow rather than an outage. Descope fails the request so you see the mistake, instead of issuing a token that differs from what the flow returned.

Failures

A flow can fail to give Descope a usable answer. The flow can time out, end with an error, fail to start, or return an output that Descope cannot read, such as claims that is not an object. The Fail Open setting decides what the client gets in each of these cases.

With Fail Open off, which is the default, Descope fails the token request with HTTP 503 and the OAuth error temporarily_unavailable. The error_description says what happened:

Causeerror_description
The flow did not finish in timeThe token hook flow did not finish within 2000ms (with the app's timeout)
The flow ended with an errorThe token hook flow failed
The flow could not startThe token hook flow could not start
The flow's output cannot be readThe token hook flow output cannot be read

A client can retry a temporarily_unavailable error, as RFC 6749 describes.

With Fail Open on, Descope issues the token without the hook's changes in all of these cases. Turn it on when the hook only enriches tokens and an outage of the systems your flow calls must not block your clients. Keep it off when the hook enforces access, for example when it rejects blocked workloads, because a failing flow would otherwise let those requests through.

Descope counts every failure in the audit trail, whichever setting the app uses.

Refresh Tokens

Descope carries the hook's last output in the refresh token. When a client refreshes, the new access token keeps the claims the hook added and removed earlier, even when refresh_token is not one of the hook's grants. A refresh token that an authorization code or CIBA flow issued has no hook output to carry, because those grants never run the hook.

When refresh_token is one of the hook's grants, the flow runs again on every refresh. Its new output replaces the carried output, so a claim that the new run does not return is no longer on the access token. The carriedClaims input holds the custom claims that the refresh token carries, so the flow can base its decision on them.

When you remove the hook from the app, Descope stops applying the carried output on the next refresh.

Audit Events

Descope records two audit events for the token hook, both with the type Warning. You can find them in the project's Audit page.

Descope counts these events instead of recording one per token request, so a flow that fails on every request does not fill your audit trail. Each event stands for all the requests with the same app, client, grant, flow, and outcome, over a few minutes or up to 1000 requests. The event includes these fields in the Data section: third_party_application_id, client_id, grant_type, flow_id, count (how many requests it stands for), and count_from (when the first of them happened).

The events do not include the user ID, because one event can stand for requests from several users.

EventWhen Descope records itExtra data
InboundAppTokenHookRejectedThe flow rejected the token request.error_code: access_denied or invalid_grant.
InboundAppTokenHookFailedThe flow did not give a usable answer, or its claims broke the rules above.reason: timeout, error, invalid_output, or invalid_claims. timeout_ms: the app's timeout. fail_open: whether Descope issued the token anyway.

The audit events never include the flow's input or output, so the claim values your flow returns do not appear in the audit trail.

Next Steps

To build the flow that the hook runs, start with Management Flows and the End action that returns its output. For the grants that run the hook, see Client Credentials, Token Exchange, JWT Bearer, and Refresh Token.

Was this helpful?

On this page