我试图在ContainerRequestFilter对象中获取方法注释。

控制者:

@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
}

应用程序:
@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>

如何设置@RolesAllowed(“ADMIN”)值,

最佳答案

你可以...

here所示,注入您的过滤器@Context ResourceInfo,并从Method获取注释

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

但...

泽西岛已经有一个 RolesAllowedDynamicFeature ,它实现了对批注@RolesAllowed@PermitAll@DenyAll的访问控制。您只需要register the feature with your application

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

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>

或在Application子类中,可以将其添加到getSingletons()getClasses()集中。哪一个没有多大区别。没有注入发生,因此仅实例化并将其添加到单例中将是安全的。

注意:第一个选项可以在任何JAX-RS 2.0应用程序中完成,而第二个则特定于Jersey。

10-07 21:23