使用Jersey的AbstractHttpContextInjectable自定义方法注释不工作

IAE*_*IAE 7 java annotations jersey dropwizard

如果以非安全的方式访问某些方法,我想限制它们.我正在创建一个@Secure注释,用于检查请求是否是通过安全通道发送的.但是,我无法创建捕获请求的HttpContext的方法injectable.

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Secure {

}

public class SecureProvider<T> implements InjectableProvider<Secure, AbstractResourceMethod> {
    @Override
    public ComponentScope getScope() {
        return ComponentScope.PerRequest;
    }

    @Override
    public Injectable<?> getInjectable(ComponentContext componentContext,
                                       Secure annotation,
                                       AbstractResourceMethod method) {
        return new SecureInjectable();
    }
}

public class SecureInjectable<T> extends AbstractHttpContextInjectable<T> {
    @Override
    public T getValue(HttpContext context) {    
        // validation here

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Dropwizard框架,因此提供程序的初始化应该像以下一样简单:

environment.addProvider(new SessionRestrictedToProvider<>(new SessionAuthenticator(), "MySession"));
environment.addProvider(new SecureProvider<>());
environment.setSessionHandler(new SessionHandler());
Run Code Online (Sandbox Code Playgroud)

用法:

@Resource
@Path("/account")
public class AccountResource {
    @GET
    @Path("/test_secure")
    @Secure
    public Response isSecure() {
        return Response.ok().build();
    }
}
Run Code Online (Sandbox Code Playgroud)

在这一点上,我假设一个HttpContext Injectable对一个方法不起作用,但我不知道我可以用什么其他选项来实现这个注释.

Ald*_*den 8

编辑这适用于JAX-RS 2.0.虽然Jersey现在是2.4.1版本,但Dropwizard仍然遗憾地使用1.17.1 :(.

您可以ContainerRequestFilter与注释一起使用.

一,注释:

// need a name binding annotation
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Secure { }
Run Code Online (Sandbox Code Playgroud)

接下来,过滤器:

// filter will only be run for methods that have @Secure annotation
@Secure
public class SecureFilter implements ContainerRequestFilter
{
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException
    {
        // check if HTTPS
        if (!requestContext.getSecurityContext().isSecure())
        {
            // if not, abort the request
            requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST)
                                             .entity("HTTPS is required.")
                                             .build());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,注册过滤器.这取决于您如何设置Jersey应用程序.以下是您可能设置的两种方式,但还有许多其他可能性,因此我不会全部介绍它们.

如果你有ResourceConfig灰熊,你会想要这个:

final ResourceConfig rc = new ResourceConfig()
            .packages("my.package.for.resources")
            .register(SecureFilter.class);
Run Code Online (Sandbox Code Playgroud)

如果您使用的是自定义应用程序模型:

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        packages("my.package.for.resources");
        register(SecureFilter.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

@Resource
@Path("/account")
public class AccountResource {

    // filter will run for this method
    @GET
    @Path("/test_secure")
    @Secure
    public Response isSecure() {
        return Response.ok().build();
    }

    // filter will NOT run for this method
    @GET
    @Path("/test_insecure")
    public Response allowInsecure() {
        return Response.ok().build();
    }
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*n R 6

如果您不想使用AOP,我认为您可以通过实现ResourceMethodDispatchProvider和ResourceMethodDispatchAdapter来实现.

public class CustomDispatchProvider implements ResourceMethodDispatchProvider {

ResourceMethodDispatchProvider provider;

CustomDispatchProvider(ResourceMethodDispatchProvider provider)
{
    this.provider = provider;
}

@Override
public RequestDispatcher create(AbstractResourceMethod abstractResourceMethod) {
    System.out.println("creating new dispatcher for " + abstractResourceMethod);

    RequestDispatcher defaultDispatcher = provider.create(abstractResourceMethod);
    if (abstractResourceMethod.getMethod().isAnnotationPresent(Secure.class))
        return new DispatcherDecorator(defaultDispatcher);
    else
        return defaultDispatcher;
}

@Provider
public static class CustomDispatchAdapter implements ResourceMethodDispatchAdapter
{

    @Override
    public ResourceMethodDispatchProvider adapt(ResourceMethodDispatchProvider provider) {
        return new CustomDispatchProvider(provider);
    }

}

public static class DispatcherDecorator implements RequestDispatcher
{
    private RequestDispatcher dispatcher;

    DispatcherDecorator(RequestDispatcher dispatcher)
    {
        this.dispatcher = dispatcher;
    }

    public void dispatch(Object resource, HttpContext context) {
        if (context.getRequest().isSecure())
        {
            System.out.println("secure request detected");
            this.dispatcher.dispatch(resource, context);
        }
        else
        {
            System.out.println("request is NOT secure");
            throw new RuntimeException("cannot access this resource over an insecure connection");
        }

    }

}
}
Run Code Online (Sandbox Code Playgroud)

在Dropwizard中,添加如下提供程序:environment.addProvider(CustomDispatchAdapter.class);