且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

EJB jax-rs资源上的Jersey自定义SecurityContext

更新时间:2023-10-05 19:10:52

您可以使用JAX-RS SecurityContext 作为API不是SPI。应用程序开发人员提供 SecurityContext 实现的情况并不常见。如果你这样做,你必须知道它只有本地JAX-RS有效性,因为它是一个特定于JAX-RS的API。 Servlet / Web容器和EJB容器都不能使用它。他们没有必要,因为Java SE和EE具有更一般的安全支持。

You can use JAX-RS SecurityContext as an API not SPI. It is uncommon for an application developer to provide a SecurityContext implementation. If you do you have to know that it has only "local JAX-RS validity" since it is a JAX-RS specific API. Neither Servlet/Web container nor EJB container work with it. They don't have to as Java SE and EE have more general security support.

如果您希望您的安全检查在Java EE应用程序中工作(即 HttpServletRequest.isUserInRole(...) EJBContext.isCallerInRole(...) javax.annotation .security EJB上的注释)您需要使用Java EE功能保护Servlet层。这意味着在 web.xml 中使用例如< security-constraint> 。您可以使用 * 作为< role-name> 意味着所有经过身份验证的用户可以调用REST API:

If you want your security checks to works in a Java EE application (i.e. HttpServletRequest.isUserInRole(...), EJBContext.isCallerInRole(...) or javax.annotation.security annotations on EJBs) you need to secure your Servlet layer using Java EE features. This means to use for example <security-constraint> in web.xml. You can use * as <role-name> meaning "all authenticated" user can call the REST API:

<security-constraint>
    <web-resource-collection>
        <url-pattern>/rest/admin/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>adminRole</role-name>
    </auth-constraint>
</security-constraint>
<security-constraint>
    <web-resource-collection>
        <url-pattern>/rest/orders/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>*</role-name> <!-- all authenticated users -->
    </auth-constraint>
</security-constraint>

如上所示,当您的Java EE应用程序受到保护时,我们可以启用 javax。 JAX-RS中的annotation.security 注释使用名为 RolesAllowedDynamicFeature

When your Java EE application is secured as shown above we can enable javax.annotation.security annotations in JAX-RS using the Jersey-specific feature called RolesAllowedDynamicFeature.

注册功能:

@ApplicationPath("/rest")
public class MyApplication extends ResourceConfig {
    public MyApplication() {
        super(AdminResource.class);
        register(RolesAllowedDynamicFeature.class);
    }
}

保护您的资源

@Path("/admin")
@RolesAllowed("adminRole")
public class AdminResource {
    @GET
    public String get() { return "GET"; }
    ...
}

参见 泽西用户指南,了解有关保护JAX-RS应用程序的更多详细信息

See Jersey User guide for more details about securing JAX-RS applications.

所以你很接近。您不需要自己实现 SecurityContext 。如果处理安全的EJB,则不得实现它。最后,您需要将JAX-RS层保护为常见的Web / Servlet应用程序。我相信你已经保护了你的网页/ HTML页面。

So you were close. You don't need to implement a SecurityContext yourself. You must not implement it if you deal with secured EJBs. And finally you need to secure your JAX-RS layer as common Web/Servlet application. I'm sure you already have secured your Web/HTML pages.