我正在使用 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";
}
与
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 中,文档说如果我有一个可选保护的资源,则创建一个自定义过滤器。我假设我需要这样做,但我不知道从哪里开始,或者我是否真的需要这样做。
最佳答案
这与其说是 dropwizard 问题,不如说是 Jersey 问题。你可以在这里看看:https://jersey.java.net/documentation/latest/filters-and-interceptors.html
基本上你想要的是:
创建一个注释,指示您要测试身份验证(例如@AuthenticatePost)
创建资源并使用@AuthenticatePost 注释正确的方法
创建您的身份验证过滤器(可能类似于您在上面所做的)。
在动态特性中,测试传入资源上是否存在注释。这对于 post 是正确的,对于 get 是错误的。然后直接在资源方法上注册 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 会检查身份验证注释是否存在。
希望对你有帮助
如果您有任何问题,请告诉我。
关于java - 如何使用自定义 Dropwizard 过滤器选择性地保护资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35732360/