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