Allow access to annotated methods only through a secure channel using AOP. Please find a solution using Guice and its AOP features (of course, you can use other AOP solutions).
You will need the Guice library (com.google.inject: guice: 3.0).
First create an annotation
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface Secure {}
then set up a set of images
public class SecurableMethodsService extends Service<Configuration> { @Override public void initialize(Bootstrap<Configuration> bootstrap) { bootstrap.addBundle(GuiceBundle.newBuilder().addModule(new SecurableMethodsDemonstrationModule()).build()); } @Override public void run(Configuration configuration, Environment environment) throws Exception { } }
module binds interceptor method
public class SecurableMethodsDemonstrationModule extends AbstractModule { @Override protected void configure() { bind(SecuredMethodsContainingResource.class); bindInterceptor(Matchers.any(), Matchers.annotatedWith(Secure.class), new OnlySecureAllowedInterceptor(getProvider(SecurityContext.class))); } }
which checks if the connection is secure (note: in this example, the resource is reported as not found, if the connection is unsafe, you may need to configure it for your use case)
public class OnlySecureAllowedInterceptor implements MethodInterceptor { private final Provider<SecurityContext> securityContextProvider; public OnlySecureAllowedInterceptor(Provider<SecurityContext> securityContextProvider) { this.securityContextProvider = securityContextProvider; } public Object invoke(MethodInvocation invocation) throws Throwable { if (!securityContextProvider.get().isSecure()) { throw new NotFoundException(); } return invocation.proceed(); } }
and finally, a resource with a protected method looks like
@Path("") public class SecuredMethodsContainingResource { @GET @Path("for-all") public String forAll() { return "for-all"; } @GET @Path("secure") @Secure public String secure() { return "secure"; } }
Jonas
source share