我只能使用 @Preauthorize 注释一个 Controller 的方法。当我尝试注释第二个 Controller 的方法时,我收到此异常:
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 (如果我仅注释此 Controller ,则一切正常):
@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 并注释其方法时,我收到开头显示的异常
@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";
}
}
我只是希望能够在不同的 Controller 上注释方法。你能告诉我如何做到这一点以及为什么我在注释另一个 Controller 的方法时会收到该异常吗?
最佳答案
在 Java 配置中使用 @PreAuthorize
注释之前,您必须执行一些必要的步骤:
在主安全配置中,您必须指定注释以启用全局方法安全性:
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true)
使用
@PreAuthorize
注解标记您想要保护的方法(顺便说一句,@Override 应该让您思考如何在接口(interface)中进行编程):@Service (value = "defaultSecuredService") public class DefaultSecuredService implements SecuredService { @Override @PreAuthorize("hasRole('ROLE_ADMIN')") public String findSimpleString() { return "simple string"; } }
确保您的 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; } }
关于java - 使用 @Preauthorize 多个 Controller 进行注释时出现 Spring Security 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20906865/