Spring Security 4.x -> 5.x 踩坑記錄
阿新 • • 發佈:2018-12-10
1. AuthenticationManager無法自動注入
在實現AbstractAuthenticationProcessingFilter重寫以使用者名稱、密碼認證時,需要顯示注入AuthenticationManager,不然會報如下錯誤:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usernamePasswordAuthenticationFilter' defined in class path resource
[com/wj/springbootdemo/modules/auth/security/SecurityConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: authenticationManager must be specified
解決辦法,顯示注入AuthenticationManager:
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
然後注入到UsernamePasswordAuthenticationFilter裡:
@Bean
public UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter () throws Exception {
UsernamePasswordAuthenticationFilter filter=new UsernamePasswordAuthenticationFilter();
filter.setAuthenticationManager(authenticationManagerBean());
return filter;
}
2.需要指定密碼加密方式
在使用Spring Security 5.x登陸頁面進行登陸時,後端會報錯:There is no PasswordEncoder mapped for the id “null”,因為5.x版本新增了多種密碼加密方式,必須指定一種,比如這樣解決:
@Bean
public static PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
下列加密方式供參考,選取一種即可:
bcrypt - BCryptPasswordEncoder (Also used for encoding)
ldap - LdapShaPasswordEncoder
MD4 - Md4PasswordEncoder
MD5 - new MessageDigestPasswordEncoder("MD5")
noop - NoOpPasswordEncoder
pbkdf2 - Pbkdf2PasswordEncoder
scrypt - SCryptPasswordEncoder
SHA-1 - new MessageDigestPasswordEncoder("SHA-1")
SHA-256 - new MessageDigestPasswordEncoder("SHA-256")
sha256 - StandardPasswordEncoder