Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS 2.0 Filter parameters via @NameBinding annotation

I've created some JAX-RS 2.0 resources (using Jeresey 2.4 running in a Servlet container) and a filter that handles authentication and authorisation that can be selectively applied via a @NameBinding annotation. This all works great.

I would like to be able to define some parameters on this annotation (specifically, security permissions that are required to access each method/resource) that can be available to the filter at runtime to alter this behaviour.

I notice that interceptors can do this via javax.ws.rs.ext.InterceptorContext.getAnnotations() but there is no equivalent in javax.ws.rs.container.ContainerRequestContext for filters. Any ideas how this may be achieved? I would like to be able to do something like the following:

@Target({TYPE, METHOD})
@Retention(value = RetentionPolicy.RUNTIME)
@NameBinding
public @interface Secured {
    String[] requiredPermissions() default {};
}

@Secured
@Priority(Priorities.AUTHENTICATION)
public class SecurityRequestFilter implements ContainerRequestFilter {
    @Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException {
        // extract credentials, verify them and check that the user has required permissions, aborting if not
    }
}

@Path("/userConfiguration/")
public class UserConfigurationResource {
    @GET
    @Produces(MediaType.APPLICATION_XML)
    @Secured(requiredPermissions = {"configuration-permission"})
    public Response getConfig(@Context HttpServletRequest httpServletRequest) {
        // produce a response
    }
}
like image 403
Zirzirikos Avatar asked Nov 05 '13 16:11

Zirzirikos


1 Answers

For a non-vendor specific solution, since JAX-RS 2.0 you can use ResourceInfo:

@Secured
@Priority(Priorities.AUTHENTICATION)
public class SecurityRequestFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        Method method = resourceInfo.getResourceMethod();

        if (method != null) {
            Secured secured = method.getAnnotation(Secured.class);
            ...
        }
    }
}
like image 160
cassiomolin Avatar answered Sep 27 '22 17:09

cassiomolin