Glassfish (Payara) REST 错误。使用自定义令牌过滤器的 403/401 邮递员请求失败

Glassfish (Payara) REST error. Postman request fails with 403/401 with custom token filter

我有 Payara 版本 182 并且有自定义令牌验证。

@Priority(Priorities.AUTHENTICATION)
public class TokenAuthenticationFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) {
    // put user into security context so it is available later for role 
     based security and application usage
     requestContext.setSecurityContext(new UserSecurityContext(currentUser, 
    requestContext.getUriInfo().getRequestUri().getScheme()));
    }
}

glassfish-web.xml :

<glassfish-web-app error-url="">
  <security-constraint>
      <web-resource-collection>
          <web-resource-name>Protected Area</web-resource-name>
          <url-pattern>/jsp/security/protected/ *</url-pattern>
          <http-method>PUT</http-method>
          <http-method>DELETE</http-method>
          <http-method>GET</http-method>
          <http-method>POST</http-method>
      </web-resource-collection>
      <auth-constraint>
          <role-name>manager</role-name>
      </auth-constraint>
    <security-role-mapping>      
      <role-name>SystemAdmin</role-name>
      <principal-name>SystemAdmin</principal-name>
      <group-name>SystemAdmin</group-name>
    </security-role-mapping>
    <security-role-mapping>
      <role-name>ADMIN</role-name>
      <principal-name>ADMIN</principal-name>
      <group-name>ADMIN</group-name>
    </security-role-mapping>
    <security-role-mapping>
      <role-name>UserRole</role-name>
      <principal-name>user</principal-name>
      <group-name>appuser</group-name>
    </security-role-mapping>
    <security-role-mapping>
      <role-name>rest-monitoring</role-name>
      <group-name>rest-monitoring</group-name>
    </security-role-mapping>
  </security-constraint>
</glassfish-web-app>

问题是当我在 Postman 中执行请求时收到 403 Forbidden。 我尝试使用 glassfish-web.xml 中的角色,然后我收到 401 并被重定向到一个页面,但这种情况发生在我成功调用方法之后控制器。即使我能够成功调用该方法,我也会收到此 401。

如果要在web.xml中指定角色,则必须在调用 JAX-RS servlet 之前对用户进行身份验证。在 JAX-RS 过滤器中进行身份验证为时已晚。

您可以使用 HttpAuthenticationMechanism as described in this article: https://www.ibm.com/developerworks/library/j-javaee8-security-api-2/index.html#ibm-h2

使用新的安全性 API 进行身份验证

问题在于,与您对用户进行身份验证的级别相比,您在更高级别定义了安全性。在 web.xml 中定义的角色比 JAX-RS 过滤器应用得更快,在用户通过身份验证之前你会得到 403。原因是 JAX-RS 是作为一个 servlet 实现的,Payara 需要先 运行 servlet,运行 是 JAX-RS 引擎,运行 是您的过滤器。但是 web.xml 中的配置甚至在 JAX-RS 引擎和您的过滤器执行之前就拒绝访问 servlet。

另一方面,HttpAuthenticationMechanism 被 Payara Server 检测到并在应用来自 web.xml 的安全检查之前执行。