mon*_*omo 5 java authentication authorization jersey dropwizard
我正在使用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";
}
Run Code Online (Sandbox Code Playgroud)
同
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());
Run Code Online (Sandbox Code Playgroud)
这似乎导致所有要求"/ protectedPing"的请求需要基本身份验证.
在Dropwizard 0.9.2中,文档说如果我有一个可选的受保护资源,则创建一个自定义过滤器.我假设我需要这样做,但我不知道从哪里开始,或者我是否真的需要做什么.
这更像是一个球衣问题,而不是一个投球手问题.你可以看看这里:https://jersey.java.net/documentation/latest/filters-and-interceptors.html
基本上你想要的是:
创建一个注释,指示您要测试身份验证(例如@AuthenticatePost)
使用@AuthenticatePost创建资源并注释正确的方法
创建您的身份验证过滤器(可能与您上面所做的类似).
在动态功能中,测试传入资源中存在的注释.这将适用于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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在使用功能上下文注册身份验证之前,DynamicFeature会检查是否存在Authenticate Annotation.
我希望有帮助,
如果您有任何疑问,请与我联系.
| 归档时间: |
|
| 查看次数: |
1815 次 |
| 最近记录: |