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

Gil*_*zan 28 java rest jax-rs resteasy

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

基本上它使用PreProcessInterceptor接口来扫描目标方法的注释(来自javax.annotation.security包),该方法描述了访问该方法所需的角色.由于此处的验证器是拦截器,它可以取消目标方法调用,如果需要则返回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<Object> singletons = new LinkedHashSet<Object>();

     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<Object> getSingletons() {
        return singletons;
    }
}
Run Code Online (Sandbox Code Playgroud)

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...
     }
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Car*_*ini 26

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)};
     }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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