如何使用自定义Dropwizardfilter可选地保护资源
我正在使用Dropwizard 0.9.2,我想创建一个不需要GET身份validation的资源,并且需要对POST进行基本身份validation。
我努力了
@Path("/protectedPing") @Produces(MediaType.TEXT_PLAIN) public class ProtectedPing { @GET public String everybody() { return "pingpong"; } @PermitAll @POST public String authenticated(){ return "secret pingpong"; }
同
CachingAuthenticator ca = new CachingAuthenticator(environment.metrics(), ldapAuthenticator, cbSpec); AdminAuthorizer authorizer = new AdminAuthorizer(); BasicCredentialAuthFilter bcaf = new BasicCredentialAuthFilter.Builder().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”的请求需要基本身份validation。
在Dropwizard 0.9.2中,文档说如果我有一个可选的受保护资源,则创建一个自定义filter。 我假设我需要这样做,但我不知道从哪里开始,或者我是否真的需要做什么。
这更像是一个jersey问题,而不是一个投球手问题。 你可以看看这里: https : //jersey.java.net/documentation/latest/filters-and-interceptors.html
基本上你想要的是:
-
创建一个注释,指示您要测试身份validation(例如@AuthenticatePost)
-
使用@AuthenticatePost创建资源并注释正确的方法
-
创建您的身份validationfilter(可能与您上面所做的类似)。
-
在动态function中,测试传入资源中存在的注释。 这将适用于post,false适用于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"; } } }
请注意,在使用function上下文注册身份validation之前,DynamicFeature会检查是否存在Authenticate Annotation。
我希望有帮助,
如果您有任何疑问,请与我联系。