我正在使用Spring 4.1.5.RELEASE和Spring Security 3.2.5.RELEASE。我正在通过Java进行所有安全配置(而不是XML)。我很难获得AuthenticationManager
的引用,以便与我的自定义usernamepassword身份验证过滤器一起使用...
@Configuration
@EnableWebSecurity
@ComponentScan(basePackages="com.mainco", excludeFilters=@ComponentScan.Filter(Controller.class))
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String ROLE3 = "ROLE3";
private static final String ROLE2 = "ROLE2";
private static final String ROLE1 = "ROLE1";
@Resource(name="userDetailsService")
private UserDetailsService userDetailsService;
@Resource(name="myAuthenticationSuccessHandler")
private MyAuthenticationSuccessHandler authSuccessHandler;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(authenticationFilter(), MyUsernamePasswordAuthenticationFilter.class);
http
.authorizeRequests()
.antMatchers("/403").permitAll()
.antMatchers("/login/**").permitAll()
.antMatchers("/resources/**").permitAll()
.antMatchers("/ROLE1/**").hasRole(ROLE1)
.antMatchers("/common/**").hasAnyRole(ROLE1, ROLE2, ROLE3)
.antMatchers("/ROLE3/**").hasAnyRole(ROLE1, ROLE2, ROLE3)
.antMatchers("/ROLE2/**").hasAnyRole(ROLE1, ROLE2)
.antMatchers("/*/**").fullyAuthenticated()
.and().formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")
.successHandler(authSuccessHandler)
.and().logout().logoutSuccessUrl("/login?logout")
.and().exceptionHandling().accessDeniedPage("/403")
.and().csrf().disable();
}
@Bean(name="passwordEncoder")
public PasswordEncoder passwordEncoder() {
return new StandardPasswordEncoder();
}
@Bean
public JSONUsernamePasswordAuthenticationFilter authenticationFilter() {
final MyUsernamePasswordAuthenticationFilter authFilter = new MyUsernamePasswordAuthenticationFilter();
authFilter.setAuthenticationSuccessHandler(authSuccessHandler);
authFilter.setUsernameParameter("username");
authFilter.setPasswordParameter("password");
return authFilter;
}
此配置在启动时失败并显示消息
“引起:java.lang.IllegalArgumentException:必须指定authenticationManager”。
如何获取AuthenticationManager
的引用以用于我的过滤器?
答案 0 :(得分:2)
您可以从WebSecurityConfigurerAdapter
覆盖AuthenticationManager
方法,将@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
公开为bean,如下所示:
SELECT *
FROM codes c
WHERE c.id > 1
AND EXISTS (
SELECT *
FROM codes x
WHERE LEFT(x.code, 3) = LEFT(c.code, 3)
AND x.id = 1
);