Im trying to get the Method annotation in ContainerRequestFilter object.
Controler:
@GET
@RolesAllowed("ADMIN")
public String message() {
return "Hello, rest12!";
}
ContainerRequestFilter :
@Provider
public class SecurityInterceptor implements javax.ws.rs.container.ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) {
//Here I need To get the @RolesAllowed("ADMIN") annotation value
}
Application :
@ApplicationPath("/rest")
public class ExpertApp extends Application {
private final HashSet<Object> singletons = new LinkedHashSet<Object>();
public ExpertApp() {
singletons.add(new SecurityInterceptor());
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
public Set<Class<?>> getClasses() {
return new HashSet<Class<?>>(Arrays.asList(UserControler.class, SearchController.class));
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- Servlet declaration can be omitted in which case it would be automatically
added by Jersey -->
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
How do I ge the @RolesAllowed("ADMIN") value,
Your ContainerRequestFilter is implemented as post-matching filters. 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.
So, @RolesAllowed("ADMIN") will block the call and your filter will never be called.
To avoid that issue, I create custom annotation; for instance:
In my webservice, I can annotate the method:
And in the filter, I check for the custom annotation:
You could...
Inject into your filter
@Context ResourceInfo
, as seen here, and get the annotation from theMethod
But...
Jersey already has a
RolesAllowedDynamicFeature
that implements the access control for the annotations@RolesAllowed
,@PermitAll
and@DenyAll
. You just need to register the feature with your applicationIn
ResourceConfig
In
web.xml
Or in your
Application
subclass, you can add it to yourgetSingletons()
orgetClasses()
set. Doesn't make much difference which one. No injections occur, so it would be safe to just instantiate it and add it to the singletons.Note: The first option can be done in any JAX-RS 2.0 application, while the second is Jersey specific.