John B
John B

Reputation: 315

How to retrieve matched resources of a request in a ContainerRequestFilter

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?

Upvotes: 13

Views: 5575

Answers (3)

Kevin L.
Kevin L.

Reputation: 336

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

Upvotes: 11

Arthur
Arthur

Reputation: 1548

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();
}

Upvotes: 5

John B
John B

Reputation: 315

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.

Upvotes: 3

Related Questions