使用 Keycloak 的安全 JEE 应用程序具有 SessionContext.getCallerPrincipal() 匿名

Secured JEE app with Keycloak have the SessionContext.getCallerPrincipal() anonymous

我有一个使用 Keycloak 保护的 JEE 服务 (JaxRx),身份验证有效,但是当我想使用 @RolesAllowed 应用安全性时,我得到 EJBAccessException

该服务部署在 Wildfly 11 中,关于文档,我使用 @SecurityDomain("keycloak") 和下一个配置文件(jboss-ejb3.xml)将安全上下文传播到 EJB 层。

<?xml version="1.0" encoding="UTF-8"?>
<jboss:jboss
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:jboss="http://www.jboss.com/xml/ns/javaee"
    xmlns:s="urn:security:1.1"
    version="3.1" impl-version="2.0">

  <assembly-descriptor>
    <s:security>
      <ejb-name>*</ejb-name>
      <s:security-domain>keycloak</s:security-domain>
    </s:security>
  </assembly-descriptor>
</jboss:jboss>

我在 Wildfly 中安装了 keycloak security-domain

我正在检查,发现 SessionContext 没有用户,但 Web 上下文有。

如图所示,在 RequestContext 中标识了请求用户,但在 SessionContext(上下文)中不存在,它显示 anonymous 而不是用户。

一些想法我的服务中可能缺少什么?

在这种情况下,我的 WEB-INF 文件夹中缺少 jboss-web.xml 文件。

我添加了一个名为 jboss-web.xml 的文件,其中包含以下内容,效果非常好。

<?xml version="1.0" encoding="UTF-8"?>
<jboss>
    <security-domain>keycloak</security-domain>
</jboss>

我也遇到了类似的问题,因为我的 EJB 不安全。必须使用 @PermitAll 或 @RolesAllowed 注释来保护 EJB。如果没有这些注释之一,您可以从 EjbContext 检索的用户主体将是匿名的。