在使用 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 适配器配置
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屋!