gpt4 book ai didi

java - 在使用 Keycloak 保护的网络应用程序中获取登录用户名

转载 作者:太空狗 更新时间:2023-10-29 22:42:36 25 4
gpt4 key购买 nike

我已经使用基于 wildfly 的标准 Keycloak 适配器通过 Keycloak 保护了一个企业应用程序。我面临的问题是调用其余 Web 服务时需要知道当前登录的用户名。如何从 Keycloak 获取登录用户信息?

我尝试使用 SecurityContextWebListener 等。但是它们都无法提供所需的详细信息。

最佳答案

您从安全上下文中获取所有用户信息。

例子:

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 configuration

关于java - 在使用 Keycloak 保护的网络应用程序中获取登录用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31864062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com