Add custom claims to Keycloak tokens from your own API
- A protocol mapper decides what goes into Keycloak's tokens. Ours calls your API at login and adds the JSON it returns as a claim.
- It calls the API once per login, gives the call a hard deadline, and fails open: if the API is down, the user still logs in, just without the claim.
- One Java class plus a services file, a 6.5 KB jar, tested on Keycloak 26.4.
Why put API data in the token?
Apps often need facts Keycloak doesn't hold: the customer's plan, their seat count, which features they've paid for. Putting them in the token means every app and API gets them at login without calling the CRM or billing system on each request.
This guide follows on from building a Keycloak webhook extension, which covers the extension basics.
The three rules that keep logins safe
| Rule | Why |
|---|---|
| One call per login | Keycloak runs the mapper for the access token, ID token and userinfo. Caching per request means the API is hit once. |
| Hard deadline | One timeout for the whole call, including connecting, so a sick API can only add that much to a login. |
| Fail open | If the API is slow or down, log it, leave the claim out and let the user in. |
Step 1: The Maven project
Same setup as an event listener (every Keycloak jar provided), plus keycloak-services, because mappers extend one of its classes.
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-services</artifactId>
<version>26.4.0</version>
<scope>provided</scope>
</dependency>Step 2: The mapper
A protocol mapper is its own factory: one class describes the admin-console form and adds the claim whenever Keycloak builds a token. The config properties you declare become the form fields, with no UI code at all.
public class ExternalClaimsMapper extends AbstractOIDCProtocolMapper
implements OIDCAccessTokenMapper, OIDCIDTokenMapper, UserInfoTokenMapper {
public static final String PROVIDER_ID = "external-claims-mapper";
static { // these become the mapper's form in the admin console
CONFIG.add(new ProviderConfigProperty(API_URL, "API URL",
"Called with ?email=<user's email>. Must return a JSON object.",
ProviderConfigProperty.STRING_TYPE, null));
CONFIG.add(new ProviderConfigProperty(TIMEOUT_MS, "Timeout (ms)",
"If the API is slower than this, the claim is left out and the login continues.",
ProviderConfigProperty.STRING_TYPE, "1500"));
OIDCAttributeMapperHelper.addTokenClaimNameConfig(CONFIG);
OIDCAttributeMapperHelper.addIncludeInTokensConfig(CONFIG, ExternalClaimsMapper.class);
}
@Override
protected void setClaim(IDToken token, ProtocolMapperModel model, UserSessionModel userSession,
KeycloakSession session, ClientSessionContext ctx) {
Map<String, Object> claims = fetch(model, userSession.getUser(), ctx);
if (claims != null) OIDCAttributeMapperHelper.mapClaim(token, model, claims);
}
}Inside fetch(), the three rules look like this:
// 1. one call per login: access token, ID token and userinfo share the result
Object cached = ctx.getAttribute(cacheKey, Object.class);
if (cached != null) return cached instanceof Map ? (Map<String, Object>) cached : null;
// 2. hard deadline for the whole call - connect, wait and read
CompletableFuture<HttpResponse<String>> call = HTTP.sendAsync(request, HttpResponse.BodyHandlers.ofString());
HttpResponse<String> response = call.get(timeout, TimeUnit.MILLISECONDS);
// 3. fail open: any error is logged and the login carries on without the claim
} catch (java.util.concurrent.TimeoutException e) {
LOG.warnf("External claims skipped for %s: API slower than %d ms", user.getUsername(), timeout);
}Why sendAsync(...).get(timeout)? We first used HttpRequest.timeout() and found it doesn't cover connecting: with the API down, logins waited longer than the configured limit. Waiting on the future enforces one deadline for everything.
Step 3: Register it and build
Mappers use their own services file: src/main/resources/META-INF/services/org.keycloak.protocol.ProtocolMapper, containing the class name. Then:
mvn -q clean package && ls -lh target/*.jar
# target/keycloak-external-claims-mapper-1.0.0.jar (6.5K)Step 4: Deploy
For the demo, a stand-in "entitlements API" plays the CRM: give it an email and it returns the customer's account, plan, seats and features.
docker network create kc-demo
docker run -d --name entitlements-api --network kc-demo -v ./entitlements-api/server.mjs:/app/server.mjs node:22-alpine node /app/server.mjs
docker run -d --name keycloak --network kc-demo -p 8180:8080 -v ./target/keycloak-external-claims-mapper-1.0.0.jar:/opt/keycloak/providers/keycloak-external-claims-mapper-1.0.0.jar -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:26.4.0 start-devCheck Keycloak loaded it:
kcadm get serverinfo | jq '.protocolMapperTypes["openid-connect"][] | select(.id=="external-claims-mapper") | {id, name, category}'
# { "id": "external-claims-mapper", "name": "External API claims", "category": "Token mapper" }Step 5: Add the mapper to a client
In the admin console: Clients → your client → Client scopes → client-dedicated → Configure a new mapper → External API claims. Fill in a name, the API URL and the token claim name, then save. It applies to the very next token, with no restart.
Step 6: Prove it, then break the API
Log in and decode the access token. In our test the claim came straight from the API, which logged exactly one request for the login:
"entitlements": {
"account": "ACME-0042",
"plan": "enterprise",
"seats": 250,
"features": ["sso", "audit-log", "api-access"]
}Then stop the API and log in again:
docker stop entitlements-api
# token endpoint: HTTP 200 in 1.7s -> the login still works
# "entitlements": null -> the claim is simply left out
# WARN ... External claims skipped for olivia: API slower than 1500 msApps must treat a missing claim as "no entitlements", never as "everything".
Before you go to production
- Authenticate the API with mTLS or a client-credentials token. Never take claims from an open endpoint.
- Keep the timeout small: when the API is sick, every login waits up to that long.
- Keep claims small: large tokens break cookies and request headers.
- If the API is rate-limited, add a short per-user cache.
- Bake the jar into the image with
kc.sh build. Mappers are an internal SPI, so pin and retest on upgrades.
Keycloak custom claims FAQ
Can't I use a Hardcoded claim or User Attribute mapper?
Those work when the data already lives in Keycloak. Use an external mapper when the source of truth is another system, like your CRM or billing platform.
What happens to logins if the API goes down?
With this mapper, nothing breaks: the login waits at most the configured timeout, then completes without the claim, and Keycloak logs a warning.
Need claims, mappers or a whole extension built? We build and harden Keycloak extensions for Australian organisations. Talk to us.