你真的不需要持有 AuthenticationManager。从HttpSecurity 的 javadoc 中,以下内容应该可以正常工作:
@Configuration
@EnableWebSecurity
public class RememberMeSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.and()
.formLogin()
.permitAll()
.and()
// Example Remember Me Configuration
.rememberMe();
}
}
当然,如果您使用全局 AuthenticationManager,这也可以:
@Configuration
@EnableWebSecurity
public class RememberMeSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.and()
.formLogin()
.permitAll()
.and()
// Example Remember Me Configuration
.rememberMe();
}
}
唯一的区别是第一个示例将 AuthenticationManger 与 HttpSecurity 隔离,而第二个示例将允许 AuthenticationManager 被全局方法安全性或另一个 HttpSecurity (WebSecurityConfigurerAdapter) 使用。
这样做的原因是 .rememberMe() 会自动找到 AuthenticationManager、UserDetailsService 并在创建 RememberMeAuthenticationFilter 时使用它。它还会创建适当的 RememberMeServices,因此无需这样做。当然,如果您想自定义 .rememberMe() ,还有其他选项,因此请参阅RememberMeConfigurer javadoc了解其他选项。
如果您真的需要对 AuthenticationManager 实例的引用,您可以执行以下操作:
@Configuration
@EnableWebSecurity
public class RememberMeSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationManagerBuilder auth;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
@Bean
public AuthenticationManager authenticationManager() {
return auth.build();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.and()
.formLogin()
.permitAll()
.and()
// Example Remember Me Configuration
.rememberMe();
}
}
如果您想拥有多个 AuthenticationManager 实例,您可以执行以下操作:
@Autowired
private ObjectPostProcessor<Object> opp;
public AuthenticationManager authenticationManager()
throws Exception {
return new AuthenticationManagerBuilder(opp)
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.and()
.build();
}
public AuthenticationManager authenticationManager2()
throws Exception {
return new AuthenticationManagerBuilder(opp)
.inMemoryAuthentication()
.withUser("admin").password("password").roles("ADMIN").and()
.and()
.build();
}
注意这几乎与您之前的事情相同,除了使用 @Autowired 注释而不是使用 QUIESENT_POST_PROCESSOR 而是使用真正的 ObjectPostProcessor
PS:感谢您试用RC2!