Token Exchange Policy Lambda
On this page
This feature requires an Enterprise plan.
1.70.0
A Token Exchange Policy lambda decides whether FusionAuth allows a token exchange request, and which audiences, scopes, and lifetime the issued token receives. FusionAuth runs this lambda for every exchange in a Tenant that uses the Lambda policy engine. The lambda runs after FusionAuth authenticates the exchanger and validates the subject token. When a requested audience matches the client Id of an Entity in another Tenant, FusionAuth denies the exchange with an invalid_target error before the lambda runs.
Lambda Structure#
The lambda must contain a function named policy with the following signature:
function policy(result, exchange, context) {
// Lambda code goes here
}
The function must declare all three parameters, even if it doesn't use them:
result: the object the lambda populates with its decision. This object is mutable.exchange: information about the exchange request. This object is read-only.context: information about the Tenant, plus access to secrets. This object is read-only.
The Admin UI fills a new lambda of this type with an example implementation.
The exchange Object#
clientIdThe client Id of the exchanger Entity.
requestedAudiencesAndResourcesThe values of the audience and resource request parameters, in that order. Empty when the request includes neither.
requestedScopesThe scopes from the scope request parameter. Empty when the request doesn't include scope.
subjectTokenClaimsThe claims of the validated subject token, such as sub, iss, aud, scope, and act. Claim values keep the types they have in the token. For example, scope is a space-delimited string.
subjectTokenValidationStatusHow FusionAuth validated the subject token. The possible values are:
AUTHORITATIVE: the subject token is an access token that this Tenant issued, verified with FusionAuth's own keys. FusionAuth uses this value whensubject_token_typeisurn:ietf:params:oauth:token-type:access_token.BEST_EFFORT: the subject token is a JWT from an issuer in the Tenant's Allowed issuers, verified with keys from the issuer's OpenID Connect discovery document. FusionAuth uses this value whensubject_token_typeisurn:ietf:params:oauth:token-type:jwt.
The context Object#
The read-only context object has the following fields:
tenantId: the Id of the Tenant processing the exchange.services: access to secrets throughcontext.services.secrets.get('<secret-name>').
The result Object#
The lambda sets result.decision to ALLOW or DENY, then populates result.granted or result.denial.
To allow an exchange, set all three fields of result.granted:
granted.aud The audiences of the issued token.
granted.scope The scopes of the issued token, as a space-delimited string or an array. To grant no scopes, use an empty array.
granted.expires_in The lifetime of the issued token, in seconds.
result.decision = 'ALLOW';
result.granted = {
aud: ['email-service'],
scope: ['email:send'],
expires_in: 300
};
To deny an exchange, set both fields of result.denial:
denial.error_code The OAuth error code to return to the client. The possible values are invalid_request, invalid_target, and unauthorized_client.
denial.error_description A description of the denial to return to the client.
result.decision = 'DENY';
result.denial = {
error_code: 'unauthorized_client',
error_description: 'This client may not exchange tokens for the requested audience.'
};
FusionAuth responds to a denied exchange with a 403 status code. The response contains the error_code value in error, the error_description value, and an error_reason of lambda_denied.
Limits on the Grant#
FusionAuth applies the following rules to an ALLOW decision before it builds the token:
- FusionAuth drops any value in
granted.audthat isn't inexchange.requestedAudiencesAndResources. If no values remain, FusionAuth denies the exchange with aninvalid_targeterror. - When the subject token has a
scopeclaim, FusionAuth drops any value ingranted.scopethat the subject token'sscopeclaim doesn't contain. If the lambda granted scopes and FusionAuth drops all of them, FusionAuth denies the exchange with aninvalid_scopeerror. - When the subject token's
scopeclaim is present but empty, FusionAuth drops every value ingranted.scopeand issues the token without scopes. - When the subject token has no
scopeclaim, FusionAuth keeps every value ingranted.scope. - FusionAuth sets the token lifetime to
granted.expires_inor the default lifetime, whichever is shorter. The default lifetime is the exchanger's Entity Type JWT duration when the Entity Type has JWT configuration enabled, and the Tenant's JWT duration otherwise.
Because FusionAuth drops every audience outside the request, FusionAuth can't allow a request that includes neither audience nor resource.
When FusionAuth drops audiences or scopes, FusionAuth writes an Information entry to the Event Log that lists the dropped values.
Errors#
FusionAuth treats the following as a lambda error and rejects the exchange:
- The lambda throws an exception.
result.decisionis neitherALLOWnorDENY.- An
ALLOWdecision is missinggrantedor any of its fields. - A
DENYdecision is missingdenialor either of its fields, or uses an unsupportederror_code.
FusionAuth responds to a lambda error with a 400 status code and an invalid_request error, and records the attempt in the token exchange audit log with the POLICY_LAMBDA_ERROR outcome. The response doesn't include exception details. FusionAuth writes the exception to the Event Log as an Error entry.
Assigning the Lambda#
To assign the lambda in the Admin UI:
- Navigate to Tenants and click on the Tenant.
- Select the OAuth tab.
- In the Token exchange settings section, set Token exchange policy engine to
Lambda. - Select the lambda in Token exchange policy lambda.
- Click .
To assign the lambda with the Tenant API, set tenant.tokenExchangeConfiguration.policyEngine to LAMBDA and tenant.tokenExchangeConfiguration.policyEngineLambdaId to the lambda's Id.
Examples#
Allow Specific Exchangers for Each Audience#
This lambda maps each exchanger to one allowed audience and a set of allowed scopes. The lambda grants the requested scopes that the rule allows. When the subject token comes from an external issuer, the lambda grants only :read scopes and a 60 second lifetime:
// lets each exchanger call one audience with a fixed set of scopes, and limits tokens from external issuers
var rules = {
'todo-service': { audience: 'email-service', scopes: ['email:send'] },
'billing-service': { audience: 'invoice-service', scopes: ['invoice:read', 'invoice:write'] }
};
function policy(result, exchange, context) {
var rule = rules[exchange.clientId];
if (!rule) {
deny(result, 'unauthorized_client', 'This client may not exchange tokens.');
return;
}
if (exchange.requestedAudiencesAndResources.indexOf(rule.audience) === -1) {
deny(result, 'invalid_target', 'The requested audience is not permitted for this client.');
return;
}
// BEST_EFFORT means the subject token came from an external issuer
var external = exchange.subjectTokenValidationStatus !== 'AUTHORITATIVE';
var scopes = exchange.requestedScopes.filter(function (scope) {
return rule.scopes.indexOf(scope) !== -1 && (!external || scope.slice(-5) === ':read');
});
result.decision = 'ALLOW';
result.granted = {
aud: [rule.audience],
scope: scopes,
expires_in: external ? 60 : 300
};
}
function deny(result, code, description) {
result.decision = 'DENY';
result.denial = { error_code: code, error_description: description };
}Call an External Authorization Service#
This lambda asks an external service like FusionAuth FGA by Permify whether to allow the exchange. The lambda reads the service's API key from a secret and calls the service with Lambda HTTP Connect. When the service denies the exchange, the lambda returns the service's reason to the client. When the service returns a status other than 200, or FusionAuth can't reach the service, the lambda logs the status and denies the exchange. An unreachable service returns a status of -1:
// asks an external authorization service whether to allow the exchange, and denies when the service can't answer
function policy(result, exchange, context) {
var response = fetch('https://authz.example.com/api/exchange', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + context.services.secrets.get('authz-api-key'),
'Content-Type': 'application/json'
},
body: JSON.stringify({
tenantId: context.tenantId,
exchanger: exchange.clientId,
subject: exchange.subjectTokenClaims.sub,
audiences: exchange.requestedAudiencesAndResources,
scopes: exchange.requestedScopes
})
});
if (response.status !== 200) {
console.error('The authorization service returned status ' + response.status + '.');
deny(result, 'invalid_request', 'The exchange could not be authorized.');
return;
}
// expects {"allowed": true, "aud": [...], "scope": [...], "expires_in": 300}
var decision = JSON.parse(response.body);
if (!decision.allowed) {
deny(result, 'unauthorized_client', decision.reason || 'The authorization service denied the exchange.');
return;
}
result.decision = 'ALLOW';
result.granted = {
aud: decision.aud,
scope: decision.scope,
expires_in: decision.expires_in
};
}
function deny(result, code, description) {
result.decision = 'DENY';
result.denial = { error_code: code, error_description: description };
}Debugging#
To troubleshoot a policy lambda:
- Enable debugging on the lambda to write
console.debug()output to the Event Log. See Console. - Enable Enable debug logging in the Tenant's token exchange settings to write the reason for each failed exchange to the Event Log.
- Review the outcome and policy decision for each attempt in the Admin UI under System -> Token Exchange Log , or with the Search the Token Exchange Audit Log API.
Related
API documentation for the FusionAuth Retrieve a Token Exchange Chain API.
API documentation for the FusionAuth Search the Token Exchange Audit Log API.
Learn how FusionAuth implements OAuth 2.0 Token Exchange (RFC 8693) so that a service can call another service on behalf of a user.
Configure FusionAuth so that one service can exchange a User's access token for a token that calls another service on that User's behalf.