Keycloak Integration: License Claims in Tokens
In short: the Keycloak documentation describes no ready-made hook that calls an external service while Keycloak builds a token. The clean route is to push: NetLicensing tells your service when a license changes, your service writes the result to a user attribute through the Keycloak Admin REST API, and a token mapper copies the attribute into the tokens at every sign-in.
This is different from Okta, Auth0 and Microsoft Entra ID, which call your service during sign-in. With Keycloak the check happens before the user signs in, so a sign-in never waits for NetLicensing.
How it works
| Step | Who | What happens |
|---|---|---|
| 1 | NetLicensing | A notification (LICENSE_CREATED, WARNING_LEVEL_CHANGED) reaches your service |
| 2 | Your service | It validates the licensee in NetLicensing (validate licensee, dryRun=true) |
| 3 | Your service | It writes licensed and license_expires to the Keycloak user with PUT /admin/realms/{realm}/users/{user-id} |
| 4 | Keycloak | A token mapper puts the attribute into the ID and access tokens when the user signs in |
Choose the Keycloak user id as the NetLicensing licensee number. The id is a UUID, and NetLicensing numbers accept letters, digits and @ + % & $ : . - _, so it fits. Your service then finds the Keycloak user without a lookup table.
Prepare Keycloak
- Declare the attribute. Keycloak disables unmanaged attributes by default. Add
licensedandlicense_expiresto the realm’s user profile (Realm settings > User profile > Attributes), or set the realm’s Unmanaged Attributes policy to Admin can edit, which allows reads and writes from the administrative context only. Do not set the policy to Enabled: that lets users submit arbitrary attributes. - Make the attribute admin-only. For a declared attribute set Who can edit to Admin. If it includes User, the user could write their own license status.
- Create a client for your service. Create a client with Client authentication and Service accounts roles enabled, and note its client secret. Give the service account a realm-management role that lets it manage users, such as
manage-users. The Admin REST API also requires a token issued for it: if you use your own client or service account, assign the built-inkc-admin-apiclient scope to that client. - Add the token mapper. In the Mappers tab of your application’s client (or of a client scope), click Configure a new mapper, select the mapper type that maps a user attribute to a claim, and set the user attribute (
licensed), the claim name and the switches Add to ID token and Add to access token. Creating protocol mappers needs permission to manage the realm. Use Client scopes evaluation in the Admin Console to see what the token for a given user and client will contain.
Your service
Keycloak signs a client in with the client credentials grant: your service calls POST /realms/{realm}/protocol/openid-connect/token with grant_type=client_credentials, the client id and the secret, and receives an access token for the Admin REST API. The service then reads the user (GET /admin/realms/{realm}/users/{user-id}), changes the attributes, and sends the user back with PUT /admin/realms/{realm}/users/{user-id}, which answers 204 No Content. A user’s attributes are a map of string arrays.
Use an API key with the role ROLE_APIKEY_LICENSEE for the validation call, the lowest role that may validate. A repeated or late notification does no harm here: the service validates again and writes the same result.
When the license simply runs out
The notifications listed in Notifications cover creations, payments and warning-level changes, and none is documented for time simply passing. The warning level is calculated when a validation request arrives (see Warning Level). Two things keep the attribute honest:
- Write the expiry date (
license_expires) next tolicensed, and let your application compare it with the current time. - Revalidate on a schedule, for example nightly for every active customer, and write the result.
A token claim is a snapshot from the moment Keycloak issues the token; the validation call in your application stays the source of truth.
Customers that are organizations
Keycloak has an Organizations feature, and its Admin REST API lists the members of an organization (GET /admin/realms/{realm}/organizations/{org-id}/members). If a license belongs to a company, use the organization id as the NetLicensing licensee number, and write the attributes to each member.
Other ways in Keycloak
- Script mapper. Keycloak can run a JavaScript OpenID Connect protocol mapper that changes the content of the ID and access token. This feature is Preview, not fully supported, and disabled by default (start the server with
--features=previewor--features=scripts). Keycloak’s documentation lists the objects the script can use (user,realm,token,userSession,keycloakSession) and does not describe calling an external service, so we do not recommend it for a license check. - Event Listener SPI. You can write an
EventListenerProvider(with itsEventListenerProviderFactory) that reacts to Keycloak events, deployed as a JAR in theprovidersdirectory followed by akc.sh build. Keycloak calls this an internal SPI that any new release can change without notice, and its guide only names the two interfaces and points to the Javadoc. Use the push route above instead.
Example: the calls
Text version of this diagram (click to expand)
- NetLicensing → Your service: notification (LICENSE_CREATED, ...)
- Your service: validate (dryRun=true)
- Your service → Keycloak: PUT .../users/{id} (licensed, license_expires)
- Keycloak → Your service: 204 No Content
Later, at sign-in
- User → Keycloak: sign in
- Keycloak → User: token with claim (token mapper)
1. NetLicensing calls your service
Create a notification of type WEBHOOK for LICENSE_CREATED and WARNING_LEVEL_CHANGED. The payload names the customer: entities.License[0].licensee for a license event and entities.Licensee[0].number for a warning-level event (see Notifications).
POST /hooks/netlicensing HTTP/1.1
Content-Type: application/json
{
"origin": "Notification",
"entities": {
"Event": [ { "name": "LICENSE_CREATED" } ],
"License": [ { "number": "LN2TD47QY", "licensee": "3f2a9c1e-7b64-4d0a-9c1e-5b8d2e4f6a10" } ]
}
}
2. Your service validates the customer
NLIC=https://go.netlicensing.io/core/v2/rest
curl --user "apiKey:$NETLICENSING_LICENSEE_KEY" --header "Accept: application/json" \
--data "dryRun=true" \
$NLIC/licensee/3f2a9c1e-7b64-4d0a-9c1e-5b8d2e4f6a10/validate
The response has one ProductModuleValidation item per product module with a valid property (models such as Rental and Multi-feature also return valid per license or feature inside the item’s list). Time-based models add expires.
3. Your service writes the attributes to Keycloak
import base64, json, os, urllib.parse, urllib.request
NLIC = "https://go.netlicensing.io/core/v2/rest"
KC = "https://keycloak.example.com"
REALM = "myrealm"
MODULE = "MGZRTP4UR" # the product module you sell
def call(method, url, headers, body=None):
req = urllib.request.Request(url, data=body, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=10) as resp:
raw = resp.read()
return json.loads(raw) if raw else None
def prop(node, name):
return next((p["value"] for p in node.get("property", []) if p["name"] == name), None)
def validate(licensee_number):
"""Ask NetLicensing without saving anything (dryRun) and return (valid, expires)."""
auth = base64.b64encode(f"apiKey:{os.environ['NETLICENSING_API_KEY']}".encode()).decode()
data = call(
"POST",
f"{NLIC}/licensee/{urllib.parse.quote(licensee_number, safe='')}/validate",
{"Authorization": f"Basic {auth}", "Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"},
b"dryRun=true",
)
for item in (data.get("items") or {}).get("item", []):
if prop(item, "productModuleNumber") == MODULE:
valid = prop(item, "valid") == "true" or any(
prop(l, "valid") == "true" for l in item.get("list", []))
return valid, prop(item, "expires")
return False, None
def keycloak_token():
body = urllib.parse.urlencode({
"grant_type": "client_credentials",
"client_id": os.environ["KC_CLIENT_ID"],
"client_secret": os.environ["KC_CLIENT_SECRET"],
}).encode()
token = call("POST", f"{KC}/realms/{REALM}/protocol/openid-connect/token",
{"Content-Type": "application/x-www-form-urlencoded"}, body)
return token["access_token"]
def set_license_attributes(user_id, valid, expires):
headers = {"Authorization": f"Bearer {keycloak_token()}", "Content-Type": "application/json"}
url = f"{KC}/admin/realms/{REALM}/users/{urllib.parse.quote(user_id, safe='')}"
user = call("GET", url, headers) # read the user first
attrs = user.get("attributes") or {}
attrs["licensed"] = ["true" if valid else "false"] # attribute values are arrays of strings
attrs["license_expires"] = [expires] if expires else []
user["attributes"] = attrs
call("PUT", url, headers, json.dumps(user).encode()) # 204 No Content
def handle_notification(payload):
entities = payload["entities"]
if "Licensee" in entities: # WARNING_LEVEL_CHANGED
number = entities["Licensee"][0]["number"]
else: # LICENSE_CREATED
number = entities["License"][0]["licensee"]
valid, expires = validate(number) # the licensee number is the Keycloak user id
set_license_attributes(number, valid, expires)
We ran this logic with stand-ins for the two HTTP services, using a real NetLicensing validation response: the calls go out in the order validate, token, read user, update user, and attributes that were already on the user stay in the request. The Keycloak calls follow the Keycloak guide and Admin REST API reference listed below.
4. Keycloak adds the claim at sign-in
With the mapper from Prepare Keycloak, the token contains the claim under the name you set. Its JSON type depends on the mapper settings; an illustration:
{
"licensed": "true",
"license_expires": "2027-11-20T00:00:00.000Z"
}
Sources
- Keycloak: Server Administration Guide (user profile and unmanaged attributes, protocol mappers, Admin REST API access, service accounts, organizations)
- Keycloak: Admin REST API reference
- Keycloak: Server Developer Guide (provider JARs, script providers, Event Listener SPI)
You run this integration yourself; NetLicensing does not host a Keycloak connector. The Keycloak details on this page are based on the sources above, and the NetLicensing calls it relies on were tested against the live API. Keycloak changes between releases, so verify the details against the linked pages for your version before you go live. Back to Identity Providers.