什么是Resteasy 3.X PreProcessInterceptor的正确替代品?

我正在使用本教程中描述的身份validation/授权机制构建rest服务: http : //howtodoinjava.com/2013/06/26/jax-rs-resteasy-basic-authentication-and-authorization-tutorial/

基本上它使用PreProcessInterceptor接口来扫描目标方法的注释(来自javax.annotation.security包),该方法描述了访问该方法所需的角色。 由于此处的validation器是拦截器,它可以取消目标方法调用,如果需要,返回401(未授权)。

这里的问题是在当前的RestEasy版本(3.0.1)中不推荐使用接口org.jboss.resteasy.spi.interception.PreProcessInterceptor,我在尝试使用标准JAX-RS接口实现相同的行为时遇到了问题。

我正在使用javax.ws.rs.ext.ReaderInterceptor接口来拦截调用。 但不知何故,服务器从不调用它:拦截器只是被忽略了。

我正在使用与之前的PreProcessInterceptor相同的方式注册拦截器/资源,并使用相同的@Provider和@ServerInterceptor注释:

ServerApplication:

public class ServerApplication extends javax.ws.rs.core.Application { private final HashSet singletons = new LinkedHashSet(); public ServerApplication() { singletons.add(new SecurityInterceptor()); singletons.add( ... ); //add each of my rest resources } @Override public Set<Class> getClasses() { HashSet<Class> set = new HashSet<Class>(); return set; } @Override public Set getSingletons() { return singletons; } } 

SecurityInterceptor:

 @Provider @ServerInterceptor public class SecurityInterceptor implements javax.ws.rs.ext.ReaderInterceptor { @Override public Object aroundReadFrom(ReaderInterceptorContext context){ //code that is never called... so lonely here... } } 

关于如何解决这个问题的任何见解?

谢谢。

RESTEasy 3.xx符合JAX-RS 2.0规范。

您尝试做的事情可以通过以下方式完成(可能更好):

 @Provider public class SecurityInterceptor implements javax.ws.rs.container.ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext){ if (not_authenticated){ requestContext.abortWith(response)}; } } 

因为只有在标准JAX-RS管道调用底层MessageBodyReader.readFrom而不是从应用程序代码调用时才调用ReaderInterceptor

但是,为什么不调用拦截器的原因可能是@ServerInterceptor注释,它是一个RESTEasy扩展。

规范在§6.5.2中规定拦截器是全局注册的,除非@Provider注释了@NameBinding注释,但我不知道RESTEasy可以处理@ServerInterceptor如果它没有显式注册,如RestEASY Interceptor所示没有被叫

如果您需要访问底层的java.lang.reflect.Method (就像您以前通过实现AcceptedByMethod可以获得的那样),您可以执行以下操作:

 ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext.getProperty("org.jboss.resteasy.core.ResourceMethodInvoker"); Method method = methodInvoker.getMethod(); 

我还想访问底层的java.lang.reflect.Method并尝试使用Resteasy 3.0.8的mtpettyp的答案,但是在getProperty调用时返回null。 我也在使用Spring和resteasy-spring,虽然我不认为这应该会影响到这一点。

如果您遇到我的情况并且正在实现匹配后的ContainerRequestFilter (如果您希望获得匹配的资源方法,则必须这样),那么您实际上可以将ContainerRequestContext转换为Resteasy为Post Match场景实现的实现。 PostMatchContainerRequestContext具有对ResourceMethodInvoker的引用。

 public void filter(ContainerRequestContext context) throws IOException { PostMatchContainerRequestContext pmContext = (PostMatchContainerRequestContext) context; Method method = pmContext.getResourceMethod().getMethod(); /* rest of code here */ }