我正在使用 Dropwizard 0.9.2,我想创建一个不需要 GET 身份验证而需要基本 POST 身份验证的资源。
我努力了
@Path("/protectedPing")
@Produces(MediaType.TEXT_PLAIN)
public class ProtectedPing {
@GET
public String everybody() {
return "pingpong";
}
@PermitAll
@POST
public String authenticated(){
return "secret pingpong";
}
with
CachingAuthenticator<BasicCredentials, User> ca = new CachingAuthenticator<>(environment.metrics(), ldapAuthenticator, cbSpec);
AdminAuthorizer authorizer = new AdminAuthorizer();
BasicCredentialAuthFilter<User> bcaf = new BasicCredentialAuthFilter.Builder<User>().setAuthenticator(ca).setRealm("test-oauth").setAuthorizer(authorizer).buildAuthFilter();
environment.jersey().register(bcaf);
environment.jersey().register(RolesAllowedDynamicFeature.class);
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
environment.jersey().register(new ProtectedPing());
这似乎导致所有对“/protectedPing”的请求都需要基本身份验证。
在 Dropwizard 0.9.2 中,文档说如果我有一个可以选择保护的资源,则创建一个自定义过滤器。我假设我需要这样做,但我不知道从哪里开始,或者这是否是我真正需要做的。
这更像是球衣问题而不是掉落向导问题。你可以在这里看看:https://jersey.java.net/documentation/latest/filters-and-interceptors.html
本质上你想要的是:
创建一个注释来指示您要测试身份验证(例如@AuthenticatePost)
创建资源并使用@AuthenticatePost注释正确的方法
创建您的身份验证过滤器(可能类似于您上面所做的那样)。
在动态功能中,测试注释是否存在于传入的资源上。这对于 post 来说是 true,对于 get 来说是 false。然后直接在资源方法上注册 AuthenticationFilter,而不是在资源上全局注册。
这将是我如何解决这个问题的半完整示例:
public class MyDynamicFeature implements DynamicFeature {
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
if(resourceInfo.getResourceMethod().getAnnotation(AuthenticateMe.class) != null ) {
context.register(MyAuthFilter.class);
}
}
public class MyAuthFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// do authentication here
}
}
public @interface AuthenticateMe {
}
@Path("myPath")
public class MyResource {
@GET
public String get() {
return "get-method";
}
@POST
@AuthenticateMe
public String post() {
return "post-method";
}
}
}
请注意,在向功能上下文注册身份验证之前,DynamicFeature 会检查身份验证注释是否存在。
我希望这有帮助,
如果您有任何疑问,请告诉我。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)