我正在使用Jersey 2开发REST API,目前我正尝试使用类似于Dropwizard中的@Auth的注释来合并基本身份验证。与
@Path("hello")
public class HelloResource {
@GET
@Produces("application/json")
public String hello(@Auth final Principal principal) {
return principal.getUsername();
}
}
hello资源调用应该被一些使用Authorization HTTP请求头中传递的凭据执行基本身份验证的代码拦截,并且成功将主体注入方法主体参数。
我已经开始创建一个@Auth解析器,见下文,但我看不到如何从中获取Authorization HTTP请求头?
@Singleton
public class AuthResolver {
public static class AuthInjectionResolver extends ParamInjectionResolver<Auth> {
public AuthInjectionResolver() {
super(AuthValueFactoryProvider.class);
}
}
@Singleton
public static class AuthValueFactoryProvider extends AbstractValueFactoryProvider {
@Inject
public AuthValueFactoryProvider(final MultivaluedParameterExtractorProvider extractorProvider, final ServiceLocator injector) {
super(extractorProvider, injector, UNKNOWN);
}
@Override
protected Factory<?> createValueFactory(final Parameter parameter) {
final Class<?> classType = parameter.getRawType();
return classType == null || !classType.equals(Principal.class) ? null :
new AbstractContainerRequestValueFactory<Principal>() {
@Override
public Principal provide() {
// Authentication?
}
};
}
}
public static class Binder extends AbstractBinder {
@Override
protected void configure() {
bind(AuthValueFactoryProvider.class).to(ValueFactoryProvider.class).in(Singleton.class);
bind(AuthInjectionResolver.class).to(
new TypeLiteral<InjectionResolver<Auth>>() {
}
).in(Singleton.class);
}
}
}
如何处理? :)
答案 0 :(得分:0)
啊,在AbstractContainerRequestValueFactory<Principal>
我可以添加
@Context private ResourceContext context;
然后从提供方法中提取HTTP请求及其头部。