本文介绍了当注解有参数时 CDI 拦截器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个 @Restricted 注释,以保护控制器方法的安全,用户只能在他们登录并具有特定角色时才能访问它们.我在使用 JSF 和 CDI 的 Tomcat 7 上,所以没有 EJB.只要注解接口没有指定任何参数,拦截器就会被调用.一旦我添加了一个 @Nonbinding Role value() default Role.ADMIN; 参数,拦截器和控制器方法都不会执行.也没有错误或异常.这是我的代码,我真的不知道它有什么问题:

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:

注释:

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

拦截器:

@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();
    }
}

控制器:

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

### 出现标记了必须更改或删除的内容才能使其再次工作.拦截器在 WEB-INF/beans.xml 中正确定义,因为它在我的注释中没有角色参数的情况下工作.

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()

推荐答案

今天我重新审视了这个特定的问题,发现它与 CDI 无关:

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

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

显然,我的示例中没有类级别的注释.所以 getAnnotation() 返回 null.相反,我应该使用以下内容:

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)

虽然我不知道为什么那里没有任何例外.也许其他一些事情正在发生,因为我将应用程序迁移到 TomEE,所以我无法再重现这些事情.

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.

这篇关于当注解有参数时 CDI 拦截器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 23:11