Custom Method Annotation using Jersey's AbstractHttpContextInjectable not Working

后端 未结 3 822
北荒
北荒 2020-12-08 09:14

I want to restrict some methods if they are being accessed in a non-secure manner. I\'m creating a @Secure annotation that checks whether or not the request was sent over se

3条回答
  •  囚心锁ツ
    2020-12-08 09:50

    If you don't want to use AOP, I think you can do this by implementing ResourceMethodDispatchProvider and ResourceMethodDispatchAdapter.

    public class CustomDispatchProvider implements ResourceMethodDispatchProvider {
    
    ResourceMethodDispatchProvider provider;
    
    CustomDispatchProvider(ResourceMethodDispatchProvider provider)
    {
        this.provider = provider;
    }
    
    @Override
    public RequestDispatcher create(AbstractResourceMethod abstractResourceMethod) {
        System.out.println("creating new dispatcher for " + abstractResourceMethod);
    
        RequestDispatcher defaultDispatcher = provider.create(abstractResourceMethod);
        if (abstractResourceMethod.getMethod().isAnnotationPresent(Secure.class))
            return new DispatcherDecorator(defaultDispatcher);
        else
            return defaultDispatcher;
    }
    
    @Provider
    public static class CustomDispatchAdapter implements ResourceMethodDispatchAdapter
    {
    
        @Override
        public ResourceMethodDispatchProvider adapt(ResourceMethodDispatchProvider provider) {
            return new CustomDispatchProvider(provider);
        }
    
    }
    
    public static class DispatcherDecorator implements RequestDispatcher
    {
        private RequestDispatcher dispatcher;
    
        DispatcherDecorator(RequestDispatcher dispatcher)
        {
            this.dispatcher = dispatcher;
        }
    
        public void dispatch(Object resource, HttpContext context) {
            if (context.getRequest().isSecure())
            {
                System.out.println("secure request detected");
                this.dispatcher.dispatch(resource, context);
            }
            else
            {
                System.out.println("request is NOT secure");
                throw new RuntimeException("cannot access this resource over an insecure connection");
            }
    
        }
    
    }
    }
    

    In Dropwizard, add the provider like this: environment.addProvider(CustomDispatchAdapter.class);

提交回复
热议问题