Pregunta

I am creating a custom authentication model for my JAX-RS API. Since I am using Java EE 6, it does not support interceptors, then I have to do it using regular filters.

I would like to annotate my JAX-RS methods according to a set of rules (like a public and a private method). To achieve this I need to access my resource methods via the filter (to be able to read the annotations).

How would I do that? Is there any other good alternatives that do not involve updating my environment to JAX-RS 2.0?

EDIT 1: I am looking for portability, unfortunately.

¿Fue útil?

Solución

We started a conversation about CDI, but the information cannot fit in a comment... So to address your concerns:

  1. CDI interceptors are portable.
  2. In order to access the HttpServletRequest, you need a front filter to put it in context (e.g. ThreadLocal or CDI's @RequestScoped together with some producer). But DeltaSpike has you covered with the servlet module. Also check out the security module.
  3. Inject the HttpServletRequest to the interceptor, no need for extra arguments on the resources themselfes.
  4. To change the returned response, just return something from the @AroundInvoke interceptor method. You can access the object returned by the original method using InvocationContext.proceed().

To sum up (almost pseudocode):

@MySecurityInterceptorBinding
public class MySecurityInterceptor {
    @Inject HttpServletRequest request;

    @AroundInvoke
    public Object secure(InvocationContext ctx) {
        // check security
        if( request.isUserInRole("foo") ) {
            Object value = ctx.proceed();
            // modify the returned value
            ((MyCustomResponseBase) value).setSecurityPassedFlag(true);
            return value;
            // or change it altogether (I'm not sure if this is entirely possible, try and see :)
            MyResponseValueWrapper w = new MyResponseValueWrapper(value);
            w.setXxxx("yyyy");
            return w;
        }
        else {
            // handle it...
        }
    }

Otros consejos

I think you can read the annotations on your class's methods by using Java's reflections API. Here is an example to read annotations from methods using reflection:

Class cls=Class.forName("first.AnnotationTest");
        Method[] methods=cls.getMethods();
        for(Method met:methods){
            Annotation[] annots=met.getAnnotations();
            for(Annotation ann:annots){
                if(ann.toString().equalsIgnoreCase("yourannotationclass")){
                    //DO Something Useful
                }
            }
        }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top