在javax servlet过滤器中,有没有办法知道请求发往哪个servlet?Servlet过滤器是否知道REST请求的目的地?
我有一些REST资源方法,用JAX-RS(@Path,@GET等)注释,并由RESTEasy进行扫描。
有一个servlet过滤器检查每个请求的用户权限,但我想区分REST资源。 (他们应该要求不同的特权。)
在此阶段,已知绑定了REST请求的资源方法?或者只有当请求到达过滤器后面的servlet时才匹配它?
谢谢!
在javax servlet过滤器中,有没有办法知道请求发往哪个servlet?Servlet过滤器是否知道REST请求的目的地?
我有一些REST资源方法,用JAX-RS(@Path,@GET等)注释,并由RESTEasy进行扫描。
有一个servlet过滤器检查每个请求的用户权限,但我想区分REST资源。 (他们应该要求不同的特权。)
在此阶段,已知绑定了REST请求的资源方法?或者只有当请求到达过滤器后面的servlet时才匹配它?
谢谢!
编号
唯一可用的信息是请求URL(路径)。
如果您真的想要一些授权相关的业务逻辑,您可以使用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)您的授权检查和pathTemplate匹配。如果你为所有资源正确地设计了你的路径(pathTemplates)(换句话说,如果你有正确的“范围”你的路径),一些正则表达式的魔力,你应该没有问题匹配用户的授权到一个特定的URL范围。例如:用户A使用令牌abc
可以在用户B使用令牌pqr
只能访问/v1/users/pqr/cars/*
不要忘了将它注册为球衣资源/过滤器只能访问/v1/users/abc/*
路径。在dropwizard我们通常做的是:
environment.jersey().register(ApiRequestsFilter.class);
我希望这有助于
可以至少3种方式实现这一点:
所有的细节可以在这里找到:Jersey Security doc
这工作得很好!我使用一个自定义接口注释了一些“角色”的资源方法。然后,我可以读取上下文对象中的方法并相应地采取行动(即,如果当前用户不具备所需角色,则中止)。谢谢! –