我正在努力使用 java 配置的 spring 安全性来配置方法安全性。我的配置工作没有任何问题,直到我在任何控制器中使用 @Secured 注释。
Spring 安全配置:(java 配置)
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/webjars/**","/css/**", "/less/**","/img/**","/js/**");
}
@Autowired
public void registerGlobal(AuthenticationManagerBuilder auth) throws Exception {
ShaPasswordEncoder shaPasswordEncoder = new ShaPasswordEncoder(256);
auth
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(getUserQuery())
.authoritiesByUsernameQuery(getAuthoritiesQuery())
.passwordEncoder(shaPasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().hasAuthority("BASIC_PERMISSION")
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/success-login", true)
.failureUrl("/error-login")
.loginProcessingUrl("/process-login")
.usernameParameter("security_username")
.passwordParameter("security_password")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login")
.logoutUrl("/logout")
.permitAll()
.and()
.rememberMe()
.key("04E87501B3F04DB297ADB74FA8BD48CA")
.and()
.csrf()
.disable();
}
private String getUserQuery() {
return "SELECT username as username, password as password, active as enabled "
+ "FROM employee "
+ "WHERE username = ?";
}
private String getAuthoritiesQuery() {
return "SELECT DISTINCT employee.username as username, permission.name as authority "
+ "FROM employee, employee_role, role, role_permission, permission "
+ "WHERE employee.id = employee_role.employee_id "
+ "AND role.id = employee_role.role_id "
+ "AND role.id = role_permission.role_id "
+ "AND permission.id = role_permission.permission_id "
+ "AND employee.username = ? "
+ "AND employee.active = 1";
}
}
一旦我将@Secured("EMPLOYEE_DELETE")
注释添加到任何控制器方法,我就会收到以下异常。
java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found []
所以我添加了一个AuthenticationManager
bean:
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
但这会导致另一个错误:
java.lang.IllegalStateException: Cannot apply org.springframework.security.config.annotation.authentication.configurers.provisioning.JdbcUserDetailsManagerConfigurer@34e81675 to already built object
看来我必须authenticationManagerBean
与配置共享,jdbcAuthentication
但我无法做到这一点。提前感谢您的帮助!