1

我试图弄清楚在球衣中注册 AuthDynamicFilter 时如何注入对象。

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

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

自定义验证过滤器

@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)
   }

}

上面的代码不会编译,因为在创建 CustomAuthFilter 时无法注入 Identity Object。

如果你去:

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

在这种情况下,httpServletRequest 将被设置为 null。

我能弄清楚如何解决这个问题的唯一方法是甚至不使用 AuthDynamicFeature ,而只使用普通的过滤器并以这种方式注入它就可以了。我想知道您将如何使用 AuthDynamicFeature 来做到这一点。

我对 dropwizard 和 jersey 还很陌生,所以请多多包涵。一些我可能搞砸的概念。

感谢任何建议,谢谢,德里克

4

1 回答 1

0

我有一个应用程序可以做到这一点。用 注释构造函数@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)
   }

}

告诉 Jersey 的依赖注入机制注入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仅在运行时知道,请使用 aSupplier<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));
于 2020-05-05T18:58:59.890 回答