package com.example.keycloakpattern; import java.util.Collection; import java.util.List; import java.util.Map; import org.springframework.core.convert.converter.Converter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; final class KeycloakRealmRoleConverter implements Converter> { @Override public Collection convert(Jwt jwt) { Map realmAccess = jwt.getClaimAsMap("realm_access"); if (realmAccess == null || !(realmAccess.get("roles") instanceof Collection roles)) { return List.of(); } return roles.stream() .filter(String.class::isInstance) .map(String.class::cast) .map(role -> new SimpleGrantedAuthority("ROLE_" + role)) .map(GrantedAuthority.class::cast) .toList(); } }