在使用Keycloak保护的Web应用程序中获取登录用户名 [英] Fetch Logged In Username in a webapp secured with Keycloak
问题描述
我使用标准的基于Wildfly的Keycloak适配器使用Keycloak获得了企业应用程序。我面临的问题是,其他Web服务在调用时需要知道当前登录的用户名。如何从Keycloak获取登录的用户信息?
I have secured an enterprise application with Keycloak using standard wildfly based Keycloak adapters. Issue that I am facing is that the rest web services when invoked, needs to know the username that is currently logged in. How do I get the logged in user information from Keycloak?
我尝试使用 SecurityContext
, WebListener
等。但是他们都没有能够提供所需的详细信息。
I tried using SecurityContext
, WebListener
etc. But none of them are able to give me the required details.
推荐答案
您从安全上下文中获取所有用户信息。
You get all user information from the security context.
示例:
public class Greeter {
@Context
SecurityContext sc;
@GET
@Produces(MediaType.APPLICATION_JSON)
public String sayHello() {
// this will set the user id as userName
String userName = sc.getUserPrincipal().getName();
if (sc.getUserPrincipal() instanceof KeycloakPrincipal) {
KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) sc.getUserPrincipal();
// this is how to get the real userName (or rather the login name)
userName = kp.getKeycloakSecurityContext().getIdToken().getPreferredUsername();
}
return "{ message : \"Hello " + userName + "\" }";
}
对于要传播的安全上下文,您必须将安全域配置为描述于:
JBoss / Wildfly Adapter配置
For the security context to be propagated you have to have a security domain configured as described in the: JBoss/Wildfly Adapter configuration
这篇关于在使用Keycloak保护的Web应用程序中获取登录用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!