我有一個Secured Spring MVC項目。我想在新帳戶成功創建時自動授權用戶。這通常在創建新帳戶的情況下完成,如下所示:Spring Security中的自動身份驗證
@Controller
@RequestMapping("/spitter")
public class SpitterController {
...
@Inject AuthenticationManager authMgr;
@Inject AccountService accountService;
...
@RequestMapping(value="/register", method=POST)
public String processRegistration(
@ModelAttribute("spitter") @Valid Spitter form,
BindingResult result) {
convertPasswordError(result);
String psswd = form.getPassword();
accountService.registerAccount(toAccount(form), psswd, result);
// Auto-Authentication
Authentication authRequest =
new UsernamePasswordAuthenticationToken(form.getUsername(), psswd);
Authentication authResult = authMgr.authenticate(authRequest);
SecurityContextHolder.getContext()
.setAuthentication(authResult);
return (result.hasErrors() ? VN_REG_FORM : VN_REG_OK);
}
...
}
我正在使用Java配置。我的安全配置文件是
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Autowired
AccountService accountService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login")
.and()
.logout()
.logoutSuccessUrl("/")
.and()
.rememberMe()
.tokenRepository(new InMemoryTokenRepositoryImpl())
.tokenValiditySeconds(2419200)
.key("spittrKey")
.and()
.httpBasic()
.realmName("Spittr")
.and()
.authorizeRequests()
.antMatchers("/user").hasAnyAuthority("admin", "user")
.antMatchers("/admin").hasAuthority("admin")
.antMatchers("spitter/me").authenticated()
.antMatchers(HttpMethod.POST, "/spittles").authenticated()
.anyRequest().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(new UserDetailsServiceAdapter(accountService))
.passwordEncoder(passwordEncoder());
}
}
如果我使用XML配置,我將有一個認證管理元素:因爲一個從http元素得到認證管理
<authentication-manager alias="authenticationManager">
...
</authentication-manager/>
其中別名設置除了authentication-manager元素之外,你必須區分這兩者。
然而,我的配置,顯然有被創建沒有的AuthenticationManager:
org.springframework.beans.factory.BeanCreationException:
...
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.security.authentication.AuthenticationManager spittr.web.SpitterController.authMngr; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}
...
這是一個有點出人意料。我認爲至少有一個這樣的bean會默認創建。我不確定最佳解決方案是什麼。