Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey 2 - ContainerRequestFilter get method annotation

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,

like image 761
MoShe Avatar asked Sep 02 '25 04:09

MoShe


1 Answers

You could...

Inject into your filter @Context ResourceInfo, as seen here, and get the annotation from the Method

RolesAllowed annot = resourceInfo.getResourceMethod().getAnnotation(RolesAllowed.class);

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 application

In ResourceConfig

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        super(MyResource.class);
        register(RolesAllowedDynamicFeature.class);
    }
}

In web.xml

<init-param>
    <param-name>jersey.config.server.provider.classnames</param-name>
    <param-value>
        org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature
    </param-value>
</init-param>

Or in your Application subclass, you can add it to your getSingletons() or getClasses() 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.

like image 55
Paul Samsotha Avatar answered Sep 04 '25 23:09

Paul Samsotha