简体   繁体   English

在Jersey 2中将主体注入资源方法

[英]Injecting principal into resource method in Jersey 2

I am developing a REST API using Jersey 2 and at the moment I am trying to incorporate basic authentication by use of an annotation similar to the @Auth found in Dropwizard. 我正在使用Jersey 2开发REST API,目前我正尝试通过使用与Dropwizard中的@Auth相似的注释来合并基本身份验证。 With

@Path("hello")
public class HelloResource {
    @GET
    @Produces("application/json")
    public String hello(@Auth final Principal principal) {
        return principal.getUsername();
    }
}

the hello resource invocation should be intercepted by some code performing basic authentication using the credentials passed in the Authorization HTTP request header and on success injecting the principal into the method principal parameter. 某些应用程序应该使用授权HTTP请求标头中传递的凭据执行基本身份验证,并成功将主体注入方法主体参数中,从而拦截hello资源调用。

I have started creating an @Auth resolver, see below, but I do not see how I can access the Authorization HTTP request header from within that? 我已经开始创建@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);
        }
    }
}

How to approach this? 如何处理呢? :) :)

Ah, in AbstractContainerRequestValueFactory<Principal> I can add 啊,在AbstractContainerRequestValueFactory<Principal>我可以添加

@Context private ResourceContext context;

and then extract the HTTP request and it's headers from there inside the provide method. 然后从Provide方法中提取HTTP请求及其标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM