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

aks*_*ppy 17 java jboss ejb keycloak

我使用标准的基于Wildfly的Keycloak适配器使用Keycloak获得了企业应用程序.我面临的问题是,其他Web服务在调用时需要知道当前登录的用户名.如何从Keycloak获取登录的用户信息?

我试着用SecurityContext,WebListener等等,但他们都不是能够给我所需的详细信息.

seb*_*enz 26

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

例:

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 + "\" }";
}
Run Code Online (Sandbox Code Playgroud)

要传播安全上下文,您必须按照以下内容配置安全域: JBoss/Wildfly Adapter配置

  • 在空指针异常的情况下,就像我在使用上面的承载令牌时遇到的那样:使用`getToken()`而不是`getIdToken()` (8认同)
  • KeyCloakPrincipal可从keycloak-core获得,适用于那些不知道它来自哪里的人 (3认同)

小智 17

您还可以将Web应用程序principal-attributekeycloak.json文件中的属性设置为preferred_username.

  • 谢谢!这是一个比接受的答案要好得多的答案,因为如果整个项目打包为EAR,你的答案允许`SessionContext.getCallerPrincipal.getName`在EJB层工作. (3认同)