簡體   English   中英

HK2 MethodInterceptor與Jersey資源

[英]HK2 MethodInterceptor with Jersey resource

如何設置aop MethodInterceptor以使用Jersey資源?

按照文檔,這是我嘗試過的方法:

步驟1-InterceptionService

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嗎? 有任何想法嗎?

另外,請不要建議ContainerRequestFilter 有關為什么我不能使用一個人來處理安全性的問題 ,請參見此問題

我認為您可能希望將其添加到您的configure()語句中,而不是調用register(MyInterceptionService.class):

bind(MyInterceptionService.class).to(InterceptionService.class).in(Singleton.class)

我不確定是否會奏效,因為我自己也沒有嘗試過,因此您的結果可能會有所不同

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM