CachingAuthenticator 在 Dropwizard 中的使用

Use of CachingAuthenticator in Dropwizard

我想放弃来自 dropwizard 的旧身份验证,这就是我使用 CachingAuthenticator 的 blow 配置的原因。

@Override 
public void run(WebConfiguration configuration, Environment environment) {
   environment.jersey().register(new ActivityResource());
    
   CachingAuthenticator<BasicCredentials, AuthUser> cachingAuthenticator =
        new CachingAuthenticator<>(environment.metrics(), new WebAuthenticator(), 
                configuration.getAuthenticationCachePolicy());
}

策略在 yml 文件中为

authenticationCachePolicy: maximumSize=10, expireAfterAccess=1m

我的问题是:

  1. 我如何注册(让它工作)cachingAuthenticator 以便对每个请求进行身份验证?

  2. 如何设置秒级expireAfterAccess?

  3. 代码有什么不对的地方,请指教...

我不知道“2)”,但对于“1)”,您只需将身份验证器连接到基本身份验证提供程序

CachingAuthenticator<BasicCredentials, AuthUser> cachingAuthenticator =
        new CachingAuthenticator<>(environment.metrics(), new WebAuthenticator(), 
                configuration.getAuthenticationCachePolicy());

environment.jersey().register(AuthFactory.binder(
            new BasicAuthFactory<>(cachingAuthenticator,
                     "Example Realm", AuthUser.class)));

工作解决方案

/** authentication config */
CachingAuthenticator<BasicCredentials, AuthUser> cachingAuthenticator = new CachingAuthenticator<>(
    environment.metrics(), new MyAuthenticator(), configuration.getAuthenticationCachePolicy());

environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<AuthUser>()
    .setAuthenticator(cachingAuthenticator).setRealm("kedar.javalkar.realm").buildAuthFilter()));

environment.jersey().register(new AuthValueFactoryProvider.Binder<>(AuthUser.class));

yml 可以有

# Caching authenticator.
authenticationCachePolicy: maximumSize=10000, expireAfterAccess=10m

# Caching authenticator.
authenticationCachePolicy: maximumSize=10000, expireAfterAccess=1s