feat: map Keycloak realm roles to Spring RBAC
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
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<Jwt, Collection<GrantedAuthority>> {
|
||||
|
||||
@Override
|
||||
public Collection<GrantedAuthority> convert(Jwt jwt) {
|
||||
Map<String, Object> 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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user