在使用Keycloak保护的Web应用程序中获取登录的用户名

我已经使用基于标准的基于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适配器配置

以上是 在使用Keycloak保护的Web应用程序中获取登录的用户名 的全部内容, 来源链接: utcz.com/qa/423138.html

回到顶部