How to retrieve matched resources of a request in a ContainerRequestFilter

巧了我就是萌 提交于 2019-12-10 12:34:03

问题


I am working on a WebService using JAX-RS/Jersey.

I've set up a ContainerRequestFilter whose purpose is to authenticate the user. I only need to protect some of the paths with authentication, the rest can be available to everyone.

I want to retrieve matchedResources / matchedResults via ExtendedUriInfo in my ContainerRequestFilter so that I can check if the path should be protected or not. Is there a way to create a filter which is invoked after ExtendedUriInfo is populated, but before the matched resource class and method is invoked?


回答1:


Here is a more general answer (for instance if you're using another jax-rs implementation like CXF):

Just add the following in your filter class as an instance variable:

@Context

ResourceInfo info;

"javax.ws.rs.container.ResourceInfo is a new JAX-RS context which can be injected into filters and interceptors and checked which resource class and method are about to be invoked."

(source : https://cwiki.apache.org/confluence/display/CXF20DOC/JAX-RS+Basics#JAX-RSBasics-ResourceInfo)

Original answer here




回答2:


Found a way to do it with ContainerRequestFilter:

public void filter(ContainerRequestContext requestContext) {
    UriRoutingContext routingContext = (UriRoutingContext) requestContext.getUriInfo();
    ResourceMethodInvoker invoker = (ResourceMethodInvoker) routingContext.getInflector();
    Class<?> className = invoker.getResourceClass();
    Method methodName = invoker.getResourceMethod();
}



回答3:


I managed to figure it out.

The approach I have found to work is to abandon doing this in the ContainerRequestFilter and create a ResourceFilterFactory instead. In the ResourceFilterFactory I can use

AbstractMethod.isAnnotationPresent(clazz)

to determine if my custom annotation is present. If my annotation is present, I can then return a list containing my AuthenticationContainerRequestFilter.

Another tip for anyone reading this answer is that injection in the ContainerRequestFilter will not work when using the ResourceFilterFactory approach. What I did was to do any injection in the ResourceFilterFactory and then pass the injected objects to the ContainerRequestFilter via its constructor.



来源:https://stackoverflow.com/questions/11811827/how-to-retrieve-matched-resources-of-a-request-in-a-containerrequestfilter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!