我正在构建一个REST服务,使用本教程中描述的身份验证/授权机制: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;
}
}
安全拦截器:
@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...
}
}
有什么见解可以帮我解决这个问题吗?
谢谢。
ContainerRequestFilter.getUriInfo().getMatchedResources()
返回匹配的资源对象列表。在那里,您可以解析与实际调用方法匹配的注释。 - Carlo PellegrinirequestContext.getUriInfo().getMatchedResources()
。无论如何,与以前的PreProcessInterceptor
不同,这种方法不太容易使用,因为我没有直接访问目标java.lang.reflect.Method
。但既然它解决了问题,我会将答案标记为已接受。 - Gilberto TorrezanrequestContext.setSecurityContext()
来注入你的身份验证,然后委托给@RolesAllowed
注解吗? - Carlo Pellegrini@Context
注释来注入ResourceInfo
将使您可以访问目标Method
。请参见相关链接:https://dev59.com/W14b5IYBdhLWcg3wZwy3#29201811 - MathieuB