我使用keycloak来保护我的servlet。我必须添加新角色并动态地将它们分配给用户。它使用admin API在keycloak中工作,但我无法弄清楚如何在servlet中获取特定用户的角色。
我试过这个解决方案,但我得到空集:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
...
KeycloakSecurityContext context = (KeycloakSecurityContext)request.getAttribute(KeycloakSecurityContext.class.getName());
Set<String> roles = AdapterUtils.getRolesFromSecurityContext((RefreshableKeycloakSecurityContext) context);
...
}
答案 0 :(得分:5)
KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();
String clientId = "securesite";
principal.getKeycloakSecurityContext().getToken().getResourceAccess(clientId).getRoles();
答案 1 :(得分:0)
如果servlet受keyclaok保护,那么您可以使用以下API获取KeycloakSecurityContext
,然后访问Set
个角色进行修改。
KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();
principal.getKeycloakSecurityContext().getToken().getRealmAccess().getRoles().add("Test-Role");
示例servlet请求可能如下所示。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
@SuppressWarnings("rawtypes")
KeycloakPrincipal principal = (KeycloakPrincipal)request.getUserPrincipal();
if (principal != null) {
//user has a valid session, we can assign role on the fly like this
principal.getKeycloakSecurityContext().getToken().getRealmAccess().getRoles().add("Test-Role");
}
}