|
| 1 | +package com.baeldung.keycloak.keycloaksoap; |
| 2 | + |
| 3 | +import org.springframework.core.convert.converter.Converter; |
| 4 | +import org.springframework.security.core.GrantedAuthority; |
| 5 | +import org.springframework.security.core.authority.SimpleGrantedAuthority; |
| 6 | +import org.springframework.security.oauth2.jwt.Jwt; |
| 7 | + |
| 8 | +import java.util.*; |
| 9 | +import java.util.stream.Collectors; |
| 10 | + |
| 11 | +public class KeycloakRoleConverter implements Converter<Jwt, Collection<GrantedAuthority>> { |
| 12 | + |
| 13 | + @Override |
| 14 | + public Collection<GrantedAuthority> convert(Jwt jwt) { |
| 15 | + Collection<GrantedAuthority> authorities = new ArrayList<>(); |
| 16 | + // Extract client roles with ROLE_ prefix |
| 17 | + authorities.addAll(extractClientRoles(jwt)); |
| 18 | + |
| 19 | + return authorities; |
| 20 | + } |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | + private Collection<GrantedAuthority> extractClientRoles(Jwt jwt) { |
| 25 | + Map<String, Object> resourceAccess = jwt.getClaim("resource_access"); |
| 26 | + if (resourceAccess == null || resourceAccess.isEmpty()) { |
| 27 | + return Collections.emptyList(); |
| 28 | + } |
| 29 | + // Replace this with your actual client ID from Keycloak |
| 30 | + String clientId = "baeldung-soap-services"; |
| 31 | + |
| 32 | + Map<String, Object> client = (Map<String, Object>) resourceAccess.get(clientId); |
| 33 | + if (client == null || client.isEmpty()) { |
| 34 | + return Collections.emptyList(); |
| 35 | + } |
| 36 | + @SuppressWarnings("unchecked") |
| 37 | + List<String> roles = (List<String>) client.get("roles"); |
| 38 | + if (roles == null) { |
| 39 | + return Collections.emptyList(); |
| 40 | + } |
| 41 | + return roles.stream() |
| 42 | + .map(role -> new SimpleGrantedAuthority("ROLE_" + role)) // Add ROLE_ prefix here |
| 43 | + .collect(Collectors.toList()); |
| 44 | + } |
| 45 | +} |
0 commit comments