Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk5 min

How to Map Keycloak Roles to Spring Security Authorities

Keycloak’s nested role claims are not Spring Security authorities by default. Find out whether the role is missing from the token or missing from Spring’s conversion.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Spring Boot API can accept a Keycloak access token and still deny a user’s role because authentication and authorization are separate: Spring can validate the JWT without converting Keycloak’s nested role claims into authorities. Keycloak’s default token places realm roles in realm_access.roles and client roles in resource_access.<client>.roles; Spring Security’s JWT defaults map scopes to SCOPE_ authorities, not those role claims. First inspect the access token sent to the API, then fix either Keycloak’s token issuance or Spring’s authority conversion.

Why a valid Keycloak token can still fail a role check

JWT authentication establishes that a token is acceptable to the resource server. Authorization then checks whether the authenticated user has the authority required by an endpoint. A token may pass validation while Spring’s GrantedAuthority collection lacks the role your rule expects.

As an Amazon Associate I earn from qualifying purchases.

Spring Security’s JWT resource-server defaults are scope-oriented: scopes become authorities prefixed with SCOPE_. A rule expecting ROLE_ADMIN will not match SCOPE_admin. Neither authority is automatically created from a nested Keycloak role claim unless you configure extraction. See Spring Security’s JWT resource-server documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Where Keycloak puts roles in the access token

By default, Keycloak’s role protocol mappers represent realm roles in realm_access.roles and client roles in resource_access.<client>.roles. The client key in the latter path is significant: the role belongs to a particular client. Mapper configuration can alter claim names or destinations, so treat these paths as defaults and inspect the token actually sent to your API. Keycloak documents the structure and protocol mappers in its Server Administration Guide 26.7.0.

Diagnose the failure in the right order

1. Inspect the bearer access token

Decode the bearer token used in the failing API request—not an ID token or a different token you obtained separately. Check whether the expected role appears, whether it is a realm or client role, and the exact capitalization and nesting. Also confirm the token is intended for this resource server.

2. If the role is absent, check Keycloak issuance

Review the user’s direct and group role assignments, composite roles, and service-account roles where applicable. Then inspect the client’s effective role-scope mappings and the roles client scope and protocol mappers. Having a role assigned to a user does not mean every client’s token will contain it: the issued roles depend on both the user’s effective roles and the roles exposed through that client’s scope.

In Keycloak’s admin console, the Client scopes evaluation view can show the effective scopes, mappers, and role-scope mappings for a particular user and client, along with a predicted token. The precise console labels and behavior vary by deployment version; the evaluation feature is described in the Keycloak 26.7.0 guide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use role-scope mappings deliberately rather than broadly exposing roles just to make an authorization check pass. Keycloak’s 26.8.0 guide describes these mappings as a way to limit which roles are declared in a token, recommends explicit mappings, and says the “Full Scope Allowed” switch is deprecated and intended for removal in a future release. Check your deployed version before relying on a particular label or behavior.

3. If the role is present, convert it in Spring

For a flat custom claim, Spring’s JwtGrantedAuthoritiesConverter can be configured with the authorities claim name and prefix. Keycloak’s default nested objects need a converter that traverses realm_access.roles, the intended client entry under resource_access, or both. Spring’s converter API documents the extension point and claim/prefix settings.

This illustrative Java fragment extracts realm roles only; adapt it to your Java and Spring versions, claim nullability, and authority-prefix policy. Add client-role extraction only for the client namespace the API intends to trust:

Rank #4
BookFactory Security Pass Down Log Book, Wire-O, 100 Pages
  • Made in USA - Proudly produced in Ohio by a Veteran-owned business
  • Comprehensive Coverage: This BookFactory log book includes essential fields such as post/shift, time of change, date, weather conditions, and a designated space for detailed notes. This ensures that all relevant information is captured and easily accessible.
  • Sturdy Cover: The trans-lux cover protects the log book from wear and tear, ensuring its longevity and maintaining the integrity of your recorded data.
  • Essential Security Tool: This log book is an indispensable tool for any organization that values security and accountability. It helps to prevent misunderstandings, improve communication, and ensure a smooth transition between shifts.
  • Wire-O with Trans-lux cover, 100 Pages, Dimensions 8.5" x 11" - (Security-Pass-Down) Reorder SKU: LOG-100-7CW-PP(Security-Pass-Down)
Map<String, Object> realmAccess = jwt.getClaim("realm_access");
if (realmAccess == null) return List.of();
Object rawRoles = realmAccess.get("roles");
if (!(rawRoles instanceof Collection<?> roles)) return List.of();
return roles.stream()
    .map(Object::toString)
    .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
    .toList();

If the API should retain both scope-derived authorities and role-derived authorities, Spring provides DelegatingJwtGrantedAuthoritiesConverter to aggregate converters; see its API documentation. Avoid turning arbitrary token claims into authorities: extract only the namespaces the API is meant to authorize.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

4. Match the authority name to the access rule

Choose one explicit naming contract from token claim to Spring authority to authorization rule. A role-style check such as hasRole("admin") conventionally tests for ROLE_admin; hasAuthority tests the literal authority string supplied. Confirm the exact matcher convention for your Spring Security version. A role can be present in the JWT and still fail if the converter emits a different name from the one the rule checks.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the fix based on what the token contains

What you find Likely issue Where to fix it
Expected role is missing from the access token User’s effective assignment, client role-scope mappings, or role protocol mappers do not produce that claim for this client. Review Keycloak assignments, effective client scopes, mappings, and evaluation output.
Role is present under realm_access.roles or the intended resource_access client entry, but absent from authorities Spring’s converter is not reading the nested claim. Configure a custom JWT authority converter for the intended role namespace.
Authority exists but endpoint still denies access The emitted authority name and authorization matcher do not agree. Align the converter’s prefix and role/authority rule.

Keep token validation separate from role debugging

If authentication itself fails, investigate issuer and signature/JWK configuration, expiry, not-before time, and resource-server setup before debugging authorization. With issuer configuration, Spring’s resource-server support validates the JWT signature and the exp, nbf, and iss claims. Role conversion cannot make an invalid token valid. The cited Spring resource-server page covers reactive configuration; applications using servlet security should consult documentation for their deployed Spring Security version and stack.

Realm roles and client roles answer different questions

Realm roles express realm-wide role assignments and appear by default in realm_access.roles. Client roles are application-specific and appear under the relevant client key in resource_access. For an API-specific permission, use and extract the intended client’s roles rather than treating every role claim in the token as interchangeable. The API’s converter and access rules should make that trust boundary explicit.

Quick Recap

SaleBestseller No. 1
SaleBestseller No. 3
Bestseller No. 4
BookFactory Security Pass Down Log Book, Wire-O, 100 Pages
BookFactory Security Pass Down Log Book, Wire-O, 100 Pages
Made in USA - Proudly produced in Ohio by a Veteran-owned business
$22.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.