我正在尝试从使用keycloak保护的Spring Boot应用程序中获取分配给特定用户的角色列表。
我已在AccessToken
配置类中声明了KeycloakWebSecurityConfigurerAdapter
bean,如下所示:
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
//other config code
@Bean
@Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public AccessToken accessToken() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
return ((KeycloakSecurityContext) ((KeycloakAuthenticationToken) request.getUserPrincipal()).getCredentials()).getToken();
}
}
现在我可以在控制器中自动装配AccessToken
,我可以获取ID和用户名等信息,但如何使用AccessToken
获取分配给用户的角色列表?< / p>
答案 0 :(得分:1)
用于资源角色映射使用
AccessToken.Access access = accessToken.getResourceAccess(clientId);
Set<String> roles = access.getRoles();
for realm role mappings use
AccessToken.Access access = accessToken.getRealmAccess();
Set<String> roles = access.getRoles();