Как вы вводите объект в AuthFilter, который требует @context для Jersey / Dropwizard - PullRequest
1 голос
/ 05 мая 2020

Я пытаюсь понять, как внедрить объект при регистрации AuthDynamicFilter в jersey.

public class CustomApplication extends Application<Configuration> {
   public void run(Configuration configuration, Environment environment) throws Exception {
      ...

      environment.jersey().register(new AuthDynamicFeature(CustomAuthFilter.class));   
      ...
   }
}

CustomAuthFilter

@PreMatching
public class CustomAuthFilter<P extends Principal> extends AuthFilter<String, P> {
   private final Object identity;

   @Context
   private HttpServletRequest httpServletRequest;

   @Context
   private HttpServletResponse httpServletResponse;

   public LcaAuthFilter(Identity identity) {
     this.identity = identity;
   }

   @Override
   public void filter(ContainerRequestContext requestContext) throws IOException {
       ...identity.process(httpServletRequest)
   }

}

Приведенный выше код не будет компилироваться, потому что нет возможности внедрить объект Identity при создании CustomAuthFilter.

Если вы go с:

   environment.jersey().register(new AuthDynamicFeature(new CustomerAuthFilter(new Identity())));

В этом случае httpServletRequest будет иметь значение null.

Единственный способ выяснить, как обойти это даже не использовать AuthDynamicFeature, а просто go с обычным фильтром и вводить его таким образом, что нормально. Мне интересно, как бы вы сделали это с помощью AuthDynamicFeature.

Я все еще новичок в dropwizard и jersey, поэтому, пожалуйста, терпите меня. Некоторые концепции, которые я мог бы запутать.

Любые советы оценены, спасибо, Дерек

1 Ответ

0 голосов
/ 05 мая 2020

У меня есть приложение, которое делает именно это. Добавьте к конструктору аннотацию @Inject:

@PreMatching
public class CustomAuthFilter<P extends Principal> extends AuthFilter<String, P> {
   private final Identity identity;

   @Context
   private HttpServletRequest httpServletRequest;

   @Context
   private HttpServletResponse httpServletResponse;

   // Annotate the ctor with @Inject
   @Inject
   public LcaAuthFilter(Identity identity) {
     this.identity = identity;
   }

   @Override
   public void filter(ContainerRequestContext requestContext) throws IOException {
       ...identity.process(httpServletRequest)
   }

}

Сообщите механизму внедрения зависимостей Джерси ввести identity с указанным вами значением:

Identity identity = getTheIdentity();
environment.jersey().register(new AbstractBinder() {
    @Override
    protected void configure() {
        bind(identity).to(Identity.class);
    }
});
environment.jersey().register(new AuthDynamicFeature(CustomAuthFilter.class));

Если identity только известно во время выполнения используйте вместо этого Supplier<Identity> (также адаптируйте свой конструктор):

Supplier<Identity> identity = getTheIdentitySupplier();
environment.jersey().register(new AbstractBinder() {
    @Override
    protected void configure() {
        bind(identity).to(new TypeLiteral<Supplier<Identity>>(){});
    }
});
environment.jersey().register(new AuthDynamicFeature(CustomAuthFilter.class));
...