Dropwizard中的多个AuthFactories

时间:2015-07-23 07:18:16

标签: dropwizard

我想在dropwizard,Basic和OAuth中使用两个不同的authfactories。像这样: -

BasicAuthFactory<UserA> authFactory = new BasicAuthFactory<UserA>(new  IngestionConsoleAuthenticator(),"SUPER SECRET STUFF", UserA.class);

OAuthFactory<UserB> authFactory2 = new OAuthFactory<UserB>(new PSVAppAuthenticator(), "Secret", UserB.class);

environment.jersey().register(AuthFactory.binder(authFactory));
environment.jersey().register(AuthFactory.binder(authFactory2));

BasicAuthFactory<UserA> authFactory = new BasicAuthFactory<UserA>(new IngestionConsoleAuthenticator(),"SUPER SECRET STUFF", UserA.class); OAuthFactory<UserB> authFactory2 = new OAuthFactory<UserB>(new PSVAppAuthenticator(), "Secret", UserB.class); environment.jersey().register(AuthFactory.binder(authFactory)); environment.jersey().register(AuthFactory.binder(authFactory2));

的资源运行良好,但@Auth UserA无法进行任何身份验证即可访问@Auth UserB。我怎样才能使两者同时工作?

2 个答案:

答案 0 :(得分:2)

  

http://www.dropwizard.io/manual/auth.html#chained-factories

@Override
public void run(ExampleConfiguration configuration,
                Environment environment) {
    ChainedAuthFactory<User> chainedFactory = new ChainedAuthFactory<>(
            new BasicAuthFactory<>(new ExampleBasicAuthenticator(), "SUPER SECRET STUFF", User.class),
            new OAuthFactory<>(new ExampleOAuthAuthenticator(), "SUPER SECRET STUFF", User.class));
    environment.jersey().register(AuthFactory.binder(chainedFactory));
}
     

为了使其正常工作,所有链式工厂必须生产相同的产品   主体类型,这里是用户。

答案 1 :(得分:0)

提示:dropwizard文档很好,所以请在那里阅读示例代码。以下示例来自Dropwizard 1.0.0 Documentation

@Override
public void run(ExampleConfiguration configuration,
                Environment environment) {
    AuthFilter basicCredentialAuthFilter = new BasicCredentialAuthFilter.Builder<>()
            .setAuthenticator(new ExampleBasicAuthenticator())
            .setAuthorizer(new ExampleAuthorizer())
            .setPrefix("Basic")
            .buildAuthFilter();

    AuthFilter oauthCredentialAuthFilter = new OAuthCredentialAuthFilter.Builder<>()
            .setAuthenticator(new ExampleOAuthAuthenticator())
            .setAuthorizer(new ExampleAuthorizer())
            .setPrefix("Bearer")
            .buildAuthFilter();

    List<AuthFilter> filters = Lists.newArrayList(basicCredentialAuthFilter, oauthCredentialAuthFilter);
    environment.jersey().register(new AuthDynamicFeature(new ChainedAuthFilter(filters)));
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    //If you want to use @Auth to inject a custom Principal type into your resource
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
}