我想在0.8.0-rc3-SNAPSHOT中使用dropwizard制作一个小应用程序。在那我想要如果任何用户将调用我的api用户应该在标题部分传递一个authtoken。我到目前为止做的是---
@Override
public void run(HelloWorldConfigurationhelloWorldConfiguration,Environment environment) throws Exception{
environment.jersey().register(new ViewResource());
environment.servlets().addFilter("MyCustomRequestFilter", new MyCustomRequestFilter())
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),false, "/*");
}
public class MyCustomRequestFilter implements ContainerRequestFilter {
@Override
public ContainerRequest filter(ContainerRequest request) {
System.out.print("test");
if ( request.getQueryParameters().containsKey("validateMeParam") ) {
/* validation logic */
}
// finished validation
return request;
}
}
我不知道自己做错了什么。它没有工作。
答案 0 :(得分:2)
ContainerRequestFilter
不是Servlet Filter
,这是您通过environment.servlets().addFilter
所假设的。这应该添加到Jersey配置中。
environment.jersey().register(MyCustomRequestFilter.class);
不要忘记过滤器类上的@Provider
注释。
<强>更新强>
我看到另一个严重问题。你说你正在使用Dropwizard 0.8.0,它使用Jersey 2.在这种情况下,你发布的ContainerRequestFilter
甚至不应该存在。在Jersey 1中,filter
方法的参数是ContainerRequest
,而泽西2中的参数是ContainerRequestContext
。请向您显示依赖项,并验证您上面的类是实际的类
答案 1 :(得分:0)
我希望您正在寻找此类样本
https://github.com/stevenalexander/dropwizard-security
/ *一个示例安全提供程序,它将在端点使用auth属性接收时查看每个请求* /
public class ExampleSecurityProvider<T> implements InjectableProvider<Auth, Parameter> {
public final static String CUSTOM_HEADER = "custom-security-token";
private final Authenticator<ExampleCredentials, T> authenticator;
public ExampleSecurityProvider(Authenticator<ExampleCredentials, T> authenticator) {
this.authenticator = authenticator;
}
private static class ExampleSecurityInjectable<T> extends AbstractHttpContextInjectable<T> {
private final Authenticator<ExampleCredentials, T> authenticator;
private final boolean required;
private ExampleSecurityInjectable(Authenticator<ExampleCredentials, T> authenticator, boolean required) {
this.authenticator = authenticator;
this.required = required;
}
@Override
public T getValue(HttpContext c) {
// This is where the credentials are extracted from the request
final String header = c.getRequest().getHeaderValue(CUSTOM_HEADER);
try {
if (header != null) {
final Optional<T> result = authenticator.authenticate(new ExampleCredentials(header));
if (result.isPresent()) {
return result.get();
}
}
} catch (AuthenticationException e) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
if (required) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
return null;
}
}