使用keycloak在servlet应用程序中获取用户角色 [英] Obtaining user roles in servlet application using keycloak
本文介绍了使用keycloak在servlet应用程序中获取用户角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用密钥斗篷来保护我的servlet.我必须添加新角色并将其动态分配给用户.它可以使用admin API在keycloak中工作,但是我不知道如何在servlet中获取特定用户的角色.
I'm using keycloak to protect my servlet. I have to add new roles and assign them to users dynamically. It works in keycloak using admin API, but I can't figure out how to obtain the roles for specific user in a servlet.
我尝试了此解决方案,但设置为空:
I tried this solution, but I get empty set:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
...
KeycloakSecurityContext context = (KeycloakSecurityContext)request.getAttribute(KeycloakSecurityContext.class.getName());
Set<String> roles = AdapterUtils.getRolesFromSecurityContext((RefreshableKeycloakSecurityContext) context);
...
}
推荐答案
@Shiva的答案对我不起作用. getRealmAccess()返回null.我们必须使用以下内容:
@Shiva's answer did not work for me. getRealmAccess() was returning null. we had to use the following:
KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();
String clientId = "securesite";
principal.getKeycloakSecurityContext().getToken().getResourceAccess(clientId).getRoles();
这篇关于使用keycloak在servlet应用程序中获取用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文