Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDI interceptor does not work when annotation has parameter

I'm trying to implement a @Restricted annotation, to secure controller methods in a way that users can only access them, when they are logged in and have a certain role. I'm on Tomcat 7 using JSF and CDI, so no EJB. The interceptor gets called as long as the annotation interface does not specify any parameters. As soon as I add a @Nonbinding Role value() default Role.ADMIN; parameter, neither the interceptor nor the controller method execute. No errors or exceptions either. Here is my code, I really don't know what's wrong with it:

Annotation:

@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface Restricted {
    @Nonbinding Role value() default Role.ADMIN; // ###
}

Interceptor:

@Interceptor
@Restricted
public class RoleBasedRestrictingInterceptor implements Serializable {
    @Inject
    ISecurityManager security;

    @AroundInvoke
    public Object intercept(final InvocationContext ctx) throws Exception {
        final Restricted annotation = ctx.getClass().getAnnotation(Restricted.class);
        log.info("Intercepted, required role is: {}", annotation.value()); // ###
        log.info("User is logged in: {}", security.isLoggedIn());
        return ctx.proceed();
    }
}

Controller:

@Named("manageUsers")
@SessionScoped
public class ManageUsersBacking extends implements Serializable {   
    @Restricted(Role.ADMIN) // ###
    public void testRestricted() {
        log.info("testRestricted()");
    }
}

The ### occurrences mark what has to be changed or removed to make it work again. The interceptor is properly defined in WEB-INF/beans.xml, since it works without the role parameter in my annotation.

16:04:33.772 [http-apr-8080-exec-11] INFO  c.m.s.RoleBasedRestrictingInterceptor - User is logged in: true
16:04:33.772 [http-apr-8080-exec-11] INFO  c.m.c.admin.ManageUsersBacking - testRestricted()
like image 735
Jack Avatar asked Mar 29 '13 18:03

Jack


1 Answers

Today I revisited this particular problem and noticed it had nothing to do with CDI:

ctx.getClass().getAnnotation(Restricted.class)

Obviously, there is no class level annotation in my example. So getAnnotation() returns null. Instead I should have used the following:

ctx.getMethod().getAnnotation(Restricted.class)

Though I don't know why there where no exceptions whatsoever. Maybe some other things were going on, that I can no longer reproduce because I migrated my application to TomEE.

like image 140
Jack Avatar answered Sep 30 '22 06:09

Jack