[英]How to get user roles from KeyCloak?
I am trying to implement SSO in our app using keycloak-spring-security-adapter.我正在尝试使用 keycloak-spring-security-adapter 在我们的应用程序中实现 SSO。 The logging itself is working fine, but inside the app we have modules availability based on user roles/groups and i am not able to get user roles from SecurityContext to show users only what they should see.
日志记录本身工作正常,但在应用程序内部,我们有基于用户角色/组的模块可用性,我无法从 SecurityContext 获取用户角色以仅向用户显示他们应该看到的内容。
SecurityContext context = SecurityContextHolder.getContext();
if(context.getAuthentication() != null) {
KeycloakPrincipal principal = (KeycloakPrincipal) context.getAuthentication().getPrincipal();
KeycloakSecurityContext session = principal.getKeycloakSecurityContext();
AccessToken accessToken = session.getToken();
AccessToken.Access realmAccess = accessToken.getRealmAccess();
logger.info("KEYCLOAK ROLES: " + realmAccess.getRoles());
above logger for my user always gives this:上面我的用户的记录器总是给出这个:
KEYCLOAK ROLES: [offline_access, uma_authorization]
And these are not the roles registered in keycloak server, because the one used for authenticating my user is:这些不是在 keycloak 服务器中注册的角色,因为用于验证我的用户的角色是:
GSAP_APPLICATION_SUPPORT
I am not able to log into the app with user that is not a member of any keycloak-registered groups so thats why i know this process works fine.我无法使用不是任何 keycloak 注册组成员的用户登录应用程序,所以这就是为什么我知道这个过程可以正常工作。
Is there a way of getting list of current user roles from keycloak based on userId/token?有没有办法根据 userId/token 从 keycloak 获取当前用户角色列表?
Hardcoding the roles checking inside the service is not a best practice, it's a common approach to divide role based functionalities by API like:对服务内部的角色检查进行硬编码不是最佳实践,它是一种通过 API 划分基于角色的功能的常用方法,例如:
api/v1/admin/**, api/v1/user/**
Using this you can restrict the access to API by roles:使用它,您可以按角色限制对 API 的访问:
http.authorizeExchange()
.pathMatchers("your_endpoint").hasAnyRole("desired_role");
PS Please pay attention that keycloak adds the "ROLE_" prefix to the rolename, so you can PS请注意keycloak在rolename后面加了“ROLE_”前缀,这样就可以
or或者
: :
Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> getJwtAuthenticationConverter() {var converter = new ReactiveJwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(jwt -> {
Map<String, Object> realmAccess = jwt.getClaim("realm_access");
Collection<String> roles = (Collection<String>) realmAccess.get("roles");
return Flux.fromIterable(roles.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.toList());
});
return converter;
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.