使用@Preauthorize多个控制器进行批注时出现Spring Security错误

时间:2014-01-03 15:20:15

标签: java spring spring-mvc spring-security annotations

我只能用@Preauthorize注释一个控制器的方法。当我尝试注释第二个控制器的方法时,我得到了这个例外:

org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter springSecurityFilterChain
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'allController' defined in file [/Users/alberto/springsource/vfabric-tc-server-developer-2.9.3.RELEASE/base-instance/wtpwebapps/sp/WEB-INF/classes/com/ap/sp/AllController.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Unexpected AOP exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodSecurityInterceptor' defined in class path resource [org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.aopalliance.intercept.MethodInterceptor org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.methodSecurityInterceptor() throws java.lang.Exception] threw exception; nested exception is java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []

我只使用java配置。 这是我的安全配置(我想接受所有请求并使用@Preauthorize在方法级别执行权限检查)

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @Autowired
    private DataSource dataSource;

     @Autowired
     public void registerGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery("SELECT username, password, enabled FROM auth_users WHERE username = ?")
                .authoritiesByUsernameQuery("SELECT username, authority FROM auth_authorities WHERE username = ?");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .anyRequest()
            .permitAll();
    }

}

这是唯一可以注释方法的控制器(如果我只注释这个控制器一切正常):

@Controller
public class SecurityController {

    private static final Logger logger = LoggerFactory.getLogger(SecurityController.class);


    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public SecResponse handleCustomException(AccessDeniedException ex) {

        logger.error("exception: " + ex.getMessage());
        SecResponse resp = new SecResponse();
        resp.status = "ERROR";
        return resp;

    }

    @PreAuthorize("hasRole('ADMIN')")
    @ResponseBody
    @RequestMapping(value = "/sec/admin", method = RequestMethod.GET)
    public SecResponse secAdmin() {

        SecResponse resp = new SecResponse();
        resp.role = Roles.ADMIN;

        return resp;
    }

    @PreAuthorize("hasRole('USER')")
    @ResponseBody
    @RequestMapping(value = "/sec/user", method = RequestMethod.GET)
    public SecResponse secUser() {

        SecResponse resp = new SecResponse();
        resp.role = Roles.USER;

        return resp;
    }       

}

当我创建一个新控制器并注释其方法时,我得到了开头显示的异常

@Controller
public class AllController {

    private static final Logger logger = LoggerFactory.getLogger(AllController.class);

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public SecResponse handleCustomException(AccessDeniedException ex) {

        logger.error("exception: " + ex.getMessage());
        SecResponse resp = new SecResponse();
        resp.status = "ERROR";
        return resp;

    }



    @PreAuthorize("hasRole('ADMIN')")   
    @ResponseBody
    @RequestMapping(value="/all/one", method = RequestMethod.GET)
    public String one() {

        return "one";
    }


}

我只是希望能够在不同的控制器上注释方法。你能告诉我怎么做以及为什么如果我注释另一个控制器的方法我会得到那个例外吗?

1 个答案:

答案 0 :(得分:1)

在Java Config中使用@PreAuthorize注释之前,您需要执行一些必需的步骤:

  1. 在主安全配置中,您必须指定用于启用全局方法安全性的注释:

    @Configuration
    @EnableWebSecurity        
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    
  2. 使用@PreAuthorize注释标记要保护的方法(顺便说一下,@ Override会让您考虑接口编程):

    @Service (value = "defaultSecuredService")
    public class DefaultSecuredService implements SecuredService {
    
        @Override
        @PreAuthorize("hasRole('ROLE_ADMIN')")
        public String findSimpleString() {
            return "simple string";
        }
    
    }
    
  3. 确保将bean添加到Spring上下文并使用INTERFACE进行实例化:

    @Controller
    public class IndexController {
    
        @Autowired
        private SecuredService defaultSecuredService;
    
        @RequestMapping (value = "/index", method = RequestMethod.GET)
        public ModelAndView getIndexPage() {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("index");
            modelAndView.addObject("simpleString", defaultSecuredService.findSimpleString());
    
            return modelAndView;
        }
    
    }