具体原理请参考Spring Boot Security原理一(八)和 Spinrg Security Authentication(一)
1 认证方式
1.1 内存中认证
@EnableWebSecurity
public class WebSecurityConfig implements WebMvcConfigurer {
@Bean
public UserDetailsService userDetailsService() throws Exception {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build());
return manager;
}
}
1.2 JDBC身份验证
@Autowired
private DataSource dataSource;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// ensure the passwords are encoded properly
UserBuilder users = User.withDefaultPasswordEncoder();
auth
.jdbcAuthentication()
.dataSource(dataSource)
.withDefaultSchema()
.withUser(users.username("user").password("password").roles("USER"))
.withUser(users.username("admin").password("password").roles("USER","ADMIN"));
}
1.3 LDAP认证
2 AuthenticationProvider
可以通过将自定义AuthenticationProvider为bean 来定义自定义身份验证。例如,以下将自定义身份验证,假设SpringAuthenticationProvider实现AuthenticationProvider:
仅在AuthenticationManagerBuilder尚未填充时使用
@Bean
public SpringAuthenticationProvider springAuthenticationProvider(){
return new SpringAuthenticationProvider();
}
3 UserDetailsService
可以通过将自定义公开UserDetailsService为bean 来定义自定义身份验证。例如,以下将自定义身份验证,假设SpringDataUserDetailsService实现UserDetailsService:
仅在AuthenticationManagerBuilder尚未填充且未AuthenticationProviderBean定义时才使用此选项。
@Bean
public SpringDataUserDetailsService springDataUserDetailsService(){
return new SpringDataUserDetailsService();
}
您还可以通过将PasswordEncoderbean 公开为bean 来自定义密码的编码方式。例如,如果使用bcrypt,则可以添加bean定义,如下所示:
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}