【问题标题】:Does a servlet filter know the destination of a REST request?servlet 过滤器是否知道 REST 请求的目的地?
【发布时间】:2015-09-01 18:20:32
【问题描述】:

在 javax servlet 过滤器中,有没有办法知道请求去往哪个 servlet?

我有一些 REST 资源方法,使用 JAX-RS(@Path、@GET 等)进行注释,并由 RESTEasy 扫描。

有一个 servlet 过滤器检查用户对每个请求的权限,但我想区分 REST 资源。 (他们应该需要不同的权限。)

在这个阶段是否知道绑定了 REST 请求的资源方法?还是只有在请求到达过滤器后面的 servlet 时才匹配?

谢谢!

【问题讨论】:

    标签: java rest authentication filter


    【解决方案1】:

    如果您真的想要一些与授权相关的业务逻辑,您可以使用ContainerRequestFilter 来实现这一点。你可以有如下的东西:

    public void filter(ContainerRequestContext crc) throws IOException {
            List<UriTemplate> matchedTemplates = uriInfo.getMatchedTemplates();
            String method = crc.getMethod().toLowerCase();
            String pathTemplate = "";
            String curTemplate = "";
            for (UriTemplate template : matchedTemplates) {
                String templateString = template.getTemplate();
                if (template.endsWithSlash()) {
                    curTemplate = templateString.substring(0, templateString.length() - 1);
                }
                else {
                    curTemplate = templateString;
                }
                pathTemplate = curTemplate + pathTemplate;
            }
       // Your authorization logic here once you have the pathTemplate.
       // pathTemplate (/v1/users/{userId}/cars/{carId}) and the HTTP method 
       // (GET, PUT..) together will determine the choice of servlet 
       // (resource) and the method within to be chosen and invoked.
    }
    

    您现在可以根据授权令牌(或您用于用户识别的任何其他内容)、称为 (GET/PUT/POST/DELETE) 的方法和匹配的路径模板进行授权检查。如果您为所有资源正确设计了路径(pathTemplates)(换句话说,如果您正确地“限定了”您的路径),一些正则表达式魔法,您应该没有问题将用户的授权匹配到特定的 url 范围。例如:用户A的token为abc只能访问/v1/users/abc/*路径,而用户B的token为pqr只能访问/v1/users/pqr/cars/*

    不要忘记将其注册为球衣资源/过滤器。在 dropwizard 中,我们通常这样做:

    environment.jersey().register(ApiRequestsFilter.class);
    

    希望对你有帮助

    【讨论】:

    • 这很好用!我使用自定义接口用一些“角色”注释了我的资源方法。然后我能够从上下文对象中的方法中读取它并采取相应的措施(也就是说,如果当前用户没有所需的角色,则中止)。谢谢!
    【解决方案2】:

    没有。

    唯一可用的信息是请求 url(路径)。

    【讨论】:

      【解决方案3】:

      您至少可以通过 3 种方式实现这一目标:

      1. 通过 web.xml
      2. 通过访问过滤器中的SecurityContext
      3. 作者 注释 javax.annotation.security

      所有细节都可以在这里找到:Jersey Security doc

      【讨论】:

        猜你喜欢
        • 2015-09-12
        • 2012-06-24
        • 1970-01-01
        • 2013-04-12
        • 2011-12-18
        • 2011-07-29
        • 2014-09-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多