EDIT this works with JAX-RS 2.0. Though Jersey is now on version 2.4.1, Dropwizard is sadly still using 1.17.1 :(.
You could use a ContainerRequestFilter
together with your annotation.
First, the annotation:
// need a name binding annotation
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Secure { }
Next, the filter:
// 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());
}
}
}
And lastly, registering the filter. This depends on how you set up your Jersey app. Here are two ways you might have set it up, but there are many other possibilities so I won't cover them all.
If you have a ResourceConfig
with grizzly, you would want this:
final ResourceConfig rc = new ResourceConfig()
.packages("my.package.for.resources")
.register(SecureFilter.class);
If you're using the custom application model:
public class MyApplication extends ResourceConfig {
public MyApplication() {
packages("my.package.for.resources");
register(SecureFilter.class);
}
}
Usage:
@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();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…