将SecurityContext信息和Request Body注入@BeanParam

时间:2015-10-27 16:41:15

标签: java rest jax-rs jersey-2.0

目前我在MessageBodyReader呈现命令对象,但我希望能够在@BeanParam中执行此操作:

  1. 注入一个派生自SecurityContext的字段(是否有某个地方可以在转换中挂钩?)。

  2. 有一个由MessageBodyReader实现的字段注入。

  3. 这可能吗?

1 个答案:

答案 0 :(得分:1)

注意:转到更新。我想 可以使用@BeanParam。虽然您需要将SecurityContext注入bean并提取名称信息。

使用@BeanParam 更正无法实现此目的。你可以以你正在做的方式使用MessageBodyReader,但IMO更像是一个黑客而不是任何东西。相反,我实现它的方式是按照它们应该使用的方式使用框架组件,这涉及自定义参数注入。

要实现这一目标,您需要两件事,ValueFactoryProvider提供参数值,InjectionResolver提供您自己的自定义注释。我不会对下面的例子做太多解释,但你可以在

中找到一个很好的解释

您可以像任何JUnit测试一样运行以下示例。一切都包含在一个班级中。这些是我使用的依赖项。

<dependency>
    <groupId>org.glassfish.jersey.test-framework.providers</groupId>
    <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
    <version>2.19</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.19</version>
    <scope>test</scope>
</dependency>

这是测试

import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.security.Principal;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Entity;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.api.InjectionResolver;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory;
import org.glassfish.jersey.server.internal.inject.AbstractValueFactoryProvider;
import org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider;
import org.glassfish.jersey.server.internal.inject.ParamInjectionResolver;
import org.glassfish.jersey.server.model.Parameter;
import org.glassfish.jersey.server.spi.internal.ValueFactoryProvider;
import org.glassfish.jersey.test.JerseyTest;
import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class CustomInjectionTest extends JerseyTest {

    @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.RUNTIME)
    public static @interface CustomParam {
    }

    public static class CustomModel {

        public String name;
        public RequestBody body;
    }

    public static class RequestBody {

        public String message;
    }

    public static class CustomParamValueFactory
            extends AbstractContainerRequestValueFactory<CustomModel> {

        @Override
        public CustomModel provide() {
            ContainerRequest request = getContainerRequest();
            String name = request.getSecurityContext().getUserPrincipal().getName();
            RequestBody body = request.readEntity(RequestBody.class);
            CustomModel model = new CustomModel();
            model.body = body;
            model.name = name;
            return model;
        }
    }

    public static class CustomValueFactoryProvider extends AbstractValueFactoryProvider {

        @Inject
        public CustomValueFactoryProvider(MultivaluedParameterExtractorProvider multiProvider,
                                          ServiceLocator locator) {
            super(multiProvider, locator, Parameter.Source.UNKNOWN);
        }

        @Override
        protected Factory<?> createValueFactory(Parameter parameter) {
            if (CustomModel.class == parameter.getType()
                    && parameter.isAnnotationPresent(CustomParam.class)) {
                return new CustomParamValueFactory();
            }
            return null;
        }  
    }

    public static class CustomParamInjectionResolver extends ParamInjectionResolver<CustomParam> {

        public CustomParamInjectionResolver() {
            super(CustomValueFactoryProvider.class);
        }
    }

    private static class CustomInjectBinder extends AbstractBinder {

        @Override
        protected void configure() {
            bind(CustomValueFactoryProvider.class)
                    .to(ValueFactoryProvider.class)
                    .in(Singleton.class);
            bind(CustomParamInjectionResolver.class)
                    .to(new TypeLiteral<InjectionResolver<CustomParam>>(){})
                    .in(Singleton.class);
        } 
    }

    private static final String PRINCIPAL_NAME = "peeskillet";

    @PreMatching
    public static class SecurityContextFilter implements ContainerRequestFilter {

        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
            requestContext.setSecurityContext(new SecurityContext(){
                public Principal getUserPrincipal() {
                    return new Principal() { 
                        public String getName() { return PRINCIPAL_NAME; }
                    };
                }
                public boolean isUserInRole(String role) { return false; }
                public boolean isSecure() { return true;}
                public String getAuthenticationScheme() { return null; }
            });   
        }  
    }

    @Path("test")
    public static class TestResource {
        @POST
        @Produces(MediaType.TEXT_PLAIN)
        @Consumes(MediaType.APPLICATION_JSON)
        public String post(@CustomParam CustomModel model) {
            return model.name + ":" + model.body.message;
        }
    }

    @Override
    public ResourceConfig configure() {
        return new ResourceConfig(TestResource.class)
                .register(SecurityContextFilter.class)
                .register(new CustomInjectBinder());
    }

    @Test
    public void should_return_name_with_body() {
        RequestBody body = new RequestBody();
        body.message = "Hello World";
        Response response = target("test").request()
                .post(Entity.json(body));
        assertEquals(200, response.getStatus());
        String responseBody = response.readEntity(String.class);
        assertEquals(PRINCIPAL_NAME + ":" + body.message, responseBody);
        System.out.println(responseBody);
    }
}

请注意,我从ContainerRequest内的CustomParamValueFactory读取了请求正文。它与我在RequestBody中的请求中通过JSON发送的@Test相同。

更新

令我惊讶的是, 可以使用@BeanParam。这是我用来测试的以下bean

public static class CustomModel {

    @Context
    public SecurityContext securityContext;
    public RequestBody body;
}

public static class RequestBody {

    public String message;
}

与之前测试的不同之处在于,我们需要注入整个name,而不是SecurityContext.Principal中的SecurityContext。注入无法从Principal获取名称,因此我们将手动执行此操作。

尽管让我感到惊讶的是,我们能够注入RequestBody实体。我不知道这是可能的。

这是完整的测试

import java.io.IOException;
import java.security.Principal;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Entity;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class CustomInjectTestTake2 extends JerseyTest {

    private static final String PRINCIPAL_NAME = "peeskillet";
    private static final String MESSAGE = "Hello World";
    private static final String RESPONSE = PRINCIPAL_NAME + ":" + MESSAGE;

    public static class CustomModel {

        @Context
        public SecurityContext securityContext;
        public RequestBody body;
    }

    public static class RequestBody {

        public String message;
    }

    @PreMatching
    public static class SecurityContextFilter implements ContainerRequestFilter {

        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
            requestContext.setSecurityContext(new SecurityContext(){
                public Principal getUserPrincipal() {
                    return new Principal() { 
                        public String getName() { return PRINCIPAL_NAME; }
                    };
                }
                public boolean isUserInRole(String role) { return false; }
                public boolean isSecure() { return true;}
                public String getAuthenticationScheme() { return null; }
            });   
        }  
    }

    @Path("test")
    public static class TestResource {
        @POST
        @Produces(MediaType.TEXT_PLAIN)
        @Consumes(MediaType.APPLICATION_JSON)
        public String post(@BeanParam CustomModel model) {
            return model.securityContext.getUserPrincipal().getName() 
                    + ":"  + model.body.message;
        }
    }

    @Override
    public ResourceConfig configure() {
        return new ResourceConfig(TestResource.class)
                .register(SecurityContextFilter.class);
    }

    @Test
    public void should_return_name_with_body() {
        RequestBody body = new RequestBody();
        body.message = "Hello World";
        Response response = target("test").request()
                .post(Entity.json(body));
        assertEquals(200, response.getStatus());
        String responseBody = response.readEntity(String.class);
        assertEquals(RESPONSE, responseBody);
        System.out.println(responseBody);
    }
}

另见: