Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Security and hardening

Spring Boot answers 403 insufficient_scope to a valid Keycloak token

Your error

WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"1 more line it can show

Fix it fast

Most common cause, 1 of 3

The rule checks a role, but Spring only maps the scope claim

Register a JwtAuthenticationConverter that keeps the scope authorities and adds Keycloak's nested role lists with the ROLE_ prefix.

Fix
@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
    SpelExpressionParser parser = new SpelExpressionParser();

    ExpressionJwtGrantedAuthoritiesConverter realmRoles =
        new ExpressionJwtGrantedAuthoritiesConverter(parser.parseExpression("[realm_access][roles]"));
    realmRoles.setAuthorityPrefix("ROLE_");

    ExpressionJwtGrantedAuthoritiesConverter clientRoles =
        new ExpressionJwtGrantedAuthoritiesConverter(parser.parseExpression("[resource_access]['my-api'][roles]"));
    clientRoles.setAuthorityPrefix("ROLE_");

    JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
    converter.setJwtGrantedAuthoritiesConverter(new DelegatingJwtGrantedAuthoritiesConverter(
        new JwtGrantedAuthoritiesConverter(), realmRoles, clientRoles));
    return converter;
}
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

A 403 with error="insufficient_scope" means Spring Security accepted the Keycloak token but found no matching authority. By default it only turns the scope claim into SCOPE_ authorities, while Keycloak puts roles under realm_access and resource_access. Map those claims with ExpressionJwtGrantedAuthoritiesConverter (Spring Security 6.4+), or make Keycloak add the scope or role to the token.

  • Applies to Keycloak 26.8.2, Spring Boot 4.2.0, Spring Security 7.2.0
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

Get a token the same way your client does, print the claims Spring could map, and compare them with the rule on the endpoint. The rule says what it wants (ROLE_ or SCOPE_), and the claims show what Keycloak actually sent.

Run this first
TOKEN=$(curl -s -X POST http://localhost:8080/realms/myrealm/protocol/openid-connect/token \
  -d "grant_type=client_credentials" -d "client_id=my-client" -d "client_secret=my-secret" \
  | jq -r '.access_token')
python3 -c 'import sys,json,base64; p=sys.argv[1].split(".")[1]; c=json.loads(base64.urlsafe_b64decode(p+"="*(-len(p)%4))); print(json.dumps({k:c.get(k) for k in ("scope","realm_access","resource_access","azp")},indent=2))' "$TOKEN"

Then find the line you see in this list and open its fix:

  1. 1The rule checks a role, but Spring only maps the scope claimThe decoded token lists the role under realm_access.roles or resource_access.<client>.roles, and the endpoint uses hasRole or hasAuthority('ROLE_...')
  2. 2The rule checks SCOPE_x, but Keycloak never put x in the scope claimThe endpoint uses hasAuthority('SCOPE_orders') and the decoded scope claim shows only values such as openid, profile and email
  3. 3The user has the role, but the client's role scope leaves it out of the tokenKeycloak shows the role on the user or service account, yet realm_access.roles in the decoded token does not include it

What does the error look like?

  • WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
  • The request requires higher privileges than provided by the access token.

Cause 1 of 3

The rule checks a role, but Spring only maps the scope claim

You seeThe decoded token lists the role under realm_access.roles or resource_access.<client>.roles, and the endpoint uses hasRole or hasAuthority('ROLE_...')

Check

Spring's resource server answers insufficient_scope whenever a bearer-authenticated request is denied, even when the rule is about roles. Out of the box it copies each value of the scope or scp claim into an authority with the SCOPE_ prefix and reads nothing else. Keycloak's roles client scope writes realm roles into realm_access and client roles into resource_access, so hasRole finds nothing to match.

Check
grep -rnE "hasRole|hasAnyRole|hasAuthority" src/main/java

Fix

Register a JwtAuthenticationConverter that keeps the scope authorities and adds Keycloak's nested role lists with the ROLE_ prefix. ExpressionJwtGrantedAuthoritiesConverter reads a nested claim through a SpEL index path; quote client IDs that contain a hyphen. Role names are copied exactly, so the spelling in the rule must match Keycloak's.

Fix
@Bean
JwtAuthenticationConverter jwtAuthenticationConverter() {
    SpelExpressionParser parser = new SpelExpressionParser();

    ExpressionJwtGrantedAuthoritiesConverter realmRoles =
        new ExpressionJwtGrantedAuthoritiesConverter(parser.parseExpression("[realm_access][roles]"));
    realmRoles.setAuthorityPrefix("ROLE_");

    ExpressionJwtGrantedAuthoritiesConverter clientRoles =
        new ExpressionJwtGrantedAuthoritiesConverter(parser.parseExpression("[resource_access]['my-api'][roles]"));
    clientRoles.setAuthorityPrefix("ROLE_");

    JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
    converter.setJwtGrantedAuthoritiesConverter(new DelegatingJwtGrantedAuthoritiesConverter(
        new JwtGrantedAuthoritiesConverter(), realmRoles, clientRoles));
    return converter;
}

Verify

The same token now gets 200 on the protected endpoint.

Verify
curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8081/api/admin

Confirmed by docs.spring.io

Did this fix it?

Cause 2 of 3

The rule checks SCOPE_x, but Keycloak never put x in the scope claim

You seeThe endpoint uses hasAuthority('SCOPE_orders') and the decoded scope claim shows only values such as openid, profile and email

Check

Keycloak writes a client scope's name into the scope claim when that client scope is applied to the token and its Include in token scope switch is on. A Default client scope is always applied; an Optional one only when the client names it in the scope parameter of its request. A scope that is not linked to the client at all never appears.

Check
Admin console: Clients > my-client > Client scopes > Evaluate (select optional scopes, open Generated access token)

Fix

Create a client scope named after the scope your API checks, link it to the calling client, and either mark it Default or have the client request it. Leave Include in token scope on.

Fix
# Default: Clients > my-client > Client scopes tab, link "orders" as Default
# Optional: the client asks for it in the authorization request
http://localhost:8080/realms/myrealm/protocol/openid-connect/auth?client_id=my-client&redirect_uri=http://localhost:3000/callback&response_type=code&scope=openid%20orders

Verify

The decoded scope claim now contains orders, and the endpoint stops returning 403.

Verify
curl -i -H "Authorization: Bearer $TOKEN" http://localhost:8081/api/orders

Confirmed by keycloak.org

Did this fix it?

Cause 3 of 3

The user has the role, but the client's role scope leaves it out of the token

You seeKeycloak shows the role on the user or service account, yet realm_access.roles in the decoded token does not include it

Check

Keycloak copies a role into an access token only when it is also inside the client's role scope mappings. Full Scope Allowed is deprecated in current Keycloak and the guide asks you to switch it off, so clients that follow that advice carry only the roles listed on their dedicated scope or linked client scopes.

Check
Admin console: Clients > my-client > Client scopes > my-client-dedicated > Scope

Fix

Add the role to the dedicated scope's Scope tab of the calling client, or to a client scope that is linked to it. Keep Full Scope Allowed off rather than switching it back on.

Fix
# Admin console path, then assign the realm role (here: admin)
Clients > my-client > Client scopes > my-client-dedicated > Scope

Verify

Evaluate shows the role in the generated access token, and a fresh token passes the hasRole check.

Verify
python3 -c 'import sys,json,base64; p=sys.argv[1].split(".")[1]; print(json.loads(base64.urlsafe_b64decode(p+"="*(-len(p)%4))).get("realm_access"))' "$TOKEN"

Confirmed by keycloak.org

Did this fix it?

How do I stop it coming back?

  • Write one test per protected endpoint that sends a token with and without the needed role, so a mapping change fails in CI instead of in production.
  • Keep each API's required roles in a Keycloak client scope that is linked as Default, instead of relying on Full Scope Allowed.
  • Decide per API whether rules use roles or scopes, and keep the converter and every hasRole or hasAuthority rule on that one style.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: Dispatch Pro.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.