【问题标题】:Spring Security error when annotating with @Preauthorize multiple controllers使用 @Preauthorize 多个控制器进行注释时出现 Spring Security 错误
【发布时间】:2014-01-21 07:30:19
【问题描述】:

我只能用@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";
    }


}

我只是希望能够在不同的控制器上注释方法。你能告诉我怎么做吗?如果我注释另一个控制器的方法,为什么会出现这个异常?

【问题讨论】:

  • 你使用什么作为 root 配置来设置 spring?

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


【解决方案1】:

在将 @PreAuthorize 注释与 Java Config 一起使用之前,您必须执行一些必需的步骤:

  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;
        }
    
    }
    

【讨论】:

    猜你喜欢
    • 2015-08-12
    • 1970-01-01
    • 2017-06-24
    • 2015-08-01
    • 2014-11-03
    • 2011-03-06
    • 2021-09-12
    • 2014-08-03
    相关资源
    最近更新 更多