我正在使用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中,文档说如果我有一个 protected 资源,则创建一个自定义过滤器。我以为我需要这样做,但是我不知道从哪里开始,或者我是否真的需要做些什么。

最佳答案

这更多的是 Jersey 问题,而不是dropwizard问题。您可以在这里看看:https://jersey.java.net/documentation/latest/filters-and-interceptors.html

本质上您想要的是:

  • 创建一个注释,指示您要测试身份验证(例如@AuthenticatePost)
  • 创建资源并使用@AuthenticatePost注释正确的方法
  • 创建您的身份验证过滤器(可能类似于您在上面所做的操作)。
  • 在动态功能中,测试注释是否存在于传入的资源中。对于发布,这将成立,对于获取,则将成立。然后,直接在资源方法上而不是在资源上全局注册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会检查是否存在身份验证注释。

    希望对您有所帮助,

    如果您有任何问题,请告诉我。

    09-09 20:00
    查看更多