Jersey Async ContainerRequestFilter

后端 未结 3 1212
挽巷
挽巷 2020-12-16 18:17

I have a Jersey REST API and am using a ContainerRequestFilter to handle authorization. I\'m also using @ManagedAsync on all endpoints so that my A

3条回答
  •  长情又很酷
    2020-12-16 18:44

    This is not built in to Jersey as of 2.7.

    @ManagedAsync is useless if you have any filters or interceptors that do any serious work (like hit a remote authorization service). They may add the ability to run filters asynchronously in the future, but for now you're on your own.

    UPDATE - there are other ways...

    After a long and perilous journey, I have found a very hacky solution that I'm using in the short term. Here is a rundown of what I tried and why it failed/worked.

    Guice AOP - failed

    I use Guice for DI (getting Guice injection to work with Jersey is a feat in itself!), so I figured I could use Guice AOP to get around the issue. Though Guice injection works, it is impossible to get Guice to create resource classes with Jersey 2, so Guice AOP cannot work with resource class methods. If you are trying desperately to get Guice to create resource classes with Jersey 2, don't waste your time because it will not work. This is a well-known problem.

    HK2 AOP - RECOMMENDED SOLUTION

    HK2 just recently released an AOP feature, see this question for details on how to get it working.

    Monitoring - also worked

    This is not for the faint of heart, and it is completely discouraged in the Jersey docs. You can register and ApplicationEventListener and override onRequest to return a RequestEventListener that listens for RESOURCE_METHOD_START and calls an authentication/authorization service. This event is triggered from the @ManagedAsync thread, which is the whole goal here. One caveat, the abortWith method is a no-op, so this won't work quite like a normal ContainerRequestFilter. Instead, you can throw an exception if auth fails instead, and register an ExceptionMapper to handle your exception. If someone is bold enough to give this a try, let me know and I'll post code.

提交回复
热议问题