Jersey2 ContainerRequestFilter not executing befor

2019-09-10 17:13发布

问题:

I am trying to get security working with my jersey2 web app.

I register RolesAllowedDynamicFeature and my Request filter with AUTHENTICATION priority in my ResourceConfig

packages("example.jersey");
register(MyRequestFilter.class, Priorities.AUTHENTICATION);
register(RolesAllowedDynamicFeature.class);

I added @RolesAllowed to the method

@RolesAllowed("quinn")
@GET
@Path("/")
public Response getIt(@Context UriInfo uriInfo) {
    return Response.ok().entity(service.get()).build();
}

In my request filter I set my security context

SecurityContext securityContext = containerRequestContext.getSecurityContext();
containerRequestContext.setSecurityContext(new MySecurityContext("gary", securityContext));

When I call the method from postman I get a 403 - Forbidden

I added logging to my request filter to see when it is called. It is NOT called.

If I remove the @RolesAllowed from the web method it does call the request filter.

It seems the Priorities.AUTHENTICATION is not making a difference.

Is there anything I'm missing?

回答1:

Your filter is implemented as a post-matching filter. It means that the filters would be applied only after a suitable resource method has been selected to process the actual request i.e. after request matching happens. Request matching is the process of finding a resource method that should be executed based on the request path and other request parameters.

@RolesAllowed blocks the selection of the particular resource method giving you the 'not executing' behavior you mentioned.

You have two options... using @PreMatching as explained here.

Or, use custom annotations as explained on a similar question.