带有 Jersey 资源的 HK2 MethodInterceptor [英] HK2 MethodInterceptor with Jersey resource
问题描述
如何设置 aop MethodInterceptor
以使用 Jersey 资源?
How can I set up an aop MethodInterceptor
to work with Jersey resources?
这是我尝试过的,遵循 this 文档:
Here is what I've tried, following this documentation:
第 1 步 - 拦截服务
public class MyInterceptionService implements InterceptionService
{
private final Provider<AuthFilter> authFilterProvider;
@Inject
public HK2MethodInterceptionService(Provider<AuthFilter> authFilterProvider)
{
this.authFilterProvider = authFilterProvider;
}
/**
* Match any class.
*/
@Override
public Filter getDescriptorFilter()
{
return BuilderHelper.allFilter();
}
/**
* Intercept all Jersey resource methods for security.
*/
@Override
@Nullable
public List<MethodInterceptor> getMethodInterceptors(final Method method)
{
// don't intercept methods with PermitAll
if (method.isAnnotationPresent(PermitAll.class))
{
return null;
}
return Collections.singletonList(new MethodInterceptor()
{
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable
{
if (!authFilterProvider.get().isAllowed(method))
{
throw new ForbiddenException();
}
return methodInvocation.proceed();
}
});
}
/**
* No constructor interception.
*/
@Override
@Nullable
public List<ConstructorInterceptor> getConstructorInterceptors(Constructor<?> constructor)
{
return null;
}
}
第 2 步 - 注册服务
public class MyResourceConfig extends ResourceConfig
{
public MyResourceConfig()
{
packages("package.with.my.resources");
// UPDATE: answer is remove this line
register(MyInterceptionService.class);
register(new AbstractBinder()
{
@Override
protected void configure()
{
bind(AuthFilter.class).to(AuthFilter.class).in(Singleton.class);
// UPDATE: answer is add the following line
// bind(MyInterceptionService.class).to(InterceptionService.class).in(Singleton.class);
}
});
}
}
但是这似乎不起作用,因为我的资源方法都没有被拦截.这可能是因为我将 @ManagedAsync
用于我的所有资源?有什么想法吗?
However this doesn't appear to work because none of my resource methods are being intercepted. Could this be because I use @ManagedAsync
with all of my resources? Any ideas?
另外,请不要建议使用 ContainerRequestFilter
.请参阅这个问题,了解为什么我不能使用一个来处理安全问题.
Also, please do not suggest a ContainerRequestFilter
. See this question for why I can't use one to handle security.
推荐答案
我认为与其调用 register(MyInterceptionService.class),不如将其添加到 configure() 语句中:
I think that rather than calling register(MyInterceptionService.class) you might want to instead add into your configure() statement:
bind(MyInterceptionService.class).to(InterceptionService.class).in(Singleton.class)
我不确定它会起作用,因为我自己没有尝试过,所以你的结果可能会有所不同,哈哈
I am not sure it will work as I have not tried it myself so your results may vary lol
这篇关于带有 Jersey 资源的 HK2 MethodInterceptor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!