Spring MVC,Rest和Shiro。 @RequiresAuthentication不起作用

时间:2014-12-29 10:26:11

标签: java spring spring-mvc shiro

我使用Spring 4.1.2,Shiro 1.2.3(核心,web,spring),我正在创建RestControllers。在类中,例如我使用@RequiresAuthentication批注来阻止访问方法。

@RestController
@RequestMapping("/api")
public class CarController {

    @RequestMapping("/secure")
    @RequiresAuthentication
    public String secure() {
        Subject subject = SecurityUtils.getSubject();
        return "Should be 'true' == " + subject.isAuthenticated();
    }


    @RequestMapping("/insecure")
    public String insecure() {
        Subject subject = SecurityUtils.getSubject();
        return "Should be 'false' == " + subject.isAuthenticated();
    }
}

不幸的是我可以访问这两种方法。由于false,它们都返回subject.isAuthenticated()。我错过了什么?

1 个答案:

答案 0 :(得分:4)

我找到了答案。我必须在代码之后添加到我的Java Spring Configuration:

// enable shiro annotations
@DependsOn("lifecycleBeanPostProcessor")
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
    DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
    proxyCreator.setProxyTargetClass(true);
    return proxyCreator;
}

// enable shiro annotations
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
    AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
    advisor.setSecurityManager(securityManager);
    return advisor;
}