Java HttpServletRequest和SecurityContext之间的区别

Java HttpServletRequest和SecurityContext之间的区别,java,jersey,Java,Jersey,我正在创建一个Jersey web服务 泽西岛文件的一部分: 通过使用@Context注释注入JAX-RS SecurityContext实例,可以获得请求的安全信息。注入的安全上下文实例提供了HttpServletRequestAPI上可用的等效功能 使用HttpServletRequest时,我可以轻松地执行以下操作: private @Context HttpServletRequest req; @Path("/testing") @POST public Response testi

我正在创建一个Jersey web服务

泽西岛文件的一部分:

通过使用@Context注释注入JAX-RS SecurityContext实例,可以获得请求的安全信息。注入的安全上下文实例提供了HttpServletRequestAPI上可用的等效功能

使用
HttpServletRequest
时,我可以轻松地执行以下操作:

private @Context HttpServletRequest req;

@Path("/testing")
@POST
public Response testing()
{
    HttpSession session = req.getSession(true);
    session.setAttribute("username", "myusername");
    return Response.noContent().build();
}
使用
SecurityContext
时,我不确定如何检索会话以及如何像在上述方法中那样在其中保存信息


更一般地说,什么时候应该使用一个而不是另一个?

您不能使用SecurityContext检索会话对象。SecurityContext接口仅处理安全性,而HttpServletRequest提供有关特定http(s)请求的所有信息,包括安全性

虽然您可以使用会话对象来实现安全性,但这样您就不用使用servlet的容器内置的任何安全特性

SecurityContext和HttpServletRequest都有一个方法

boolean isUserInRole(String role)
可用于检索登录用户的角色,并在服务器上执行适当的操作(例如,根据角色返回不同的资源)

您可以在web.xml中定义角色(在不使用SecurityContext的情况下)

现在,即使您没有显式调用SecurityContext.isUserInRole(角色),Jersey也会在内部执行此检查。这里可以找到一个使用SecurityContext的完整示例


至于何时使用其中一种,请在Jersey中使用SecurityContext(只使用注释更容易、更灵活)

web.xml文件在哪里?我没有。。仅获取Maven的pom.xml、Hibernate的配置文件或Jersey的config.yml。它应位于WEB-INF文件夹中。不过,如果您使用的是SecurityContext,则不需要将安全相关信息添加到web.xml中。您可能没有web.xml(新的servlet规范不需要它,因为所有内容都可以使用注释进行配置)如果您可以添加一个示例,说明我如何分配具有特定角色的用户,以及如何处理从网站客户端发送的密码,我将接受答案。我的答案中已经给出了一个完整的示例(链接到示例)。请注意,该示例在数据库中存储用户名、密码和角色。当然,您必须在请求中发送用户名和密码。也可以使用容器的身份验证/授权,但必须在user.xml中添加角色、名称和密码(请参阅)
<security-constraint>
        <web-resource-collection>
        <url-pattern>/rest/admin/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
        <role-name>admin</role-name>
        </auth-constraint>
        </security-constraint>
        <security-constraint>
        <web-resource-collection>
        <url-pattern>/rest/orders/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
        <role-name>customer</role-name>
        </auth-constraint>
        </security-constraint>
        <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>my-default-realm</realm-name>
        </login-config>
@Path("/")
@PermitAll
public class Resource {
@RolesAllowed("user")
@GET
public String get() { return "GET"; }

@RolesAllowed("admin")
@POST
public String post(String content) { return content; }