栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Java中使用Jersey安全性注释绕过Servlet过滤器中的路径

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Java中使用Jersey安全性注释绕过Servlet过滤器中的路径

由于您正在执行身份验证和/或授权,因此我建议您使用名称绑定过滤器来代替servlet过滤器,以便您可以轻松地将它们绑定到所需的资源。

要将过滤器绑定到您的REST端点,JAX-
RS提供了元注释

@NameBinding
,可以如下使用:

@NameBinding@Retention(RUNTIME)@Target({TYPE, METHOD})public @interface Secured { }

@Secured
注释将被用来装饰一个过滤器类,它实现
ContainerRequestFilter
,让您处理请求。

ContainerRequestContext
帮助你提取HTTP请求信息(更多详情,看看该
ContainerRequestContext
API):

@Secured@Provider@Priority(Priorities.AUTHENTICATION)public class SecurityFilter implements ContainerRequestFilter {    @Override    public void filter(ContainerRequestContext requestContext) throws IOException {        // Use the ContainerRequestContext to extract information from the HTTP request        // Information such as the URI, headers and HTTP entity are available    }}

ContainerRequestFilter#filter()
如果用户未通过身份验证/授权,则该方法是中止请求的好地方。为此,您可以使用
ContainerRequestContext#abortWith()
或引发异常。

@Provider
注释标记的扩展接口,应该由JAX-
RS是可发现的实现过程中提供扫描相运行时。

要将过滤器绑定到端点方法或类,请使用

@Secured
上面创建的注释对它们进行 注释。对于带有注释的方法和/或类,将执行过滤器。

@Path("/")public class MyEndpoint {    @GET    @Path("{id}")    @Produces("application/json")    public Response myUnsecuredMethod(@PathParam("id") Long id) {        // This method is not annotated with @Secured        // The security filter won't be executed before invoking this method        ...    }    @DELETE    @Secured    @Path("{id}")    @Produces("application/json")    public Response mySecuredMethod(@PathParam("id") Long id) {        // This method is annotated with @Secured        // The security filter will be executed before invoking this method        ...    }}

在上面的示例中,安全过滤器仅针对进行执行,

mySecuredMethod(Long)
因为它带有注释
@Secured

您可以根据需要为REST端点设置任意数量的过滤器。为了确保过滤器的执行顺序,请使用注释它们

@Priority

强烈建议使用

Priorities
该类中定义的值之一(将使用以下顺序):

  • AUTHENTICATION
  • AUTHORIZATION
  • ENTITY_CODER
  • HEADER_DECORATOR
  • USER

如果您的过滤器未使用注释

@Priority
,则将
USER
优先执行过滤器。

您可以将此方法与Jersey安全机制结合使用。

此外,你可以注入

ResourceInfo
你的
ContainerRequestFilter

    @Context    private ResourceInfo resourceInfo;

它可以用来获取

Method
Class
与请求的URL匹配:

    Class<?> resourceClass = resourceInfo.getResourceClass();    Method resourceMethod = resourceInfo.getResourceMethod();

并从中提取注释:

    Annotation[] annotations = resourceClass.getDeclaredAnnotations();    PermitAll annotation = resourceMethod.getAnnotation(PermitAll.class);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/419448.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号