Spring Security - PasswordEncoder

SpringBoot 在认证时的密码hash的实装
Spring Security4.2.2.RELEASE的 PasswordEncoder 关系图
在这里插入图片描述
以前介绍过 NoOpPasswordEncoder,为了测试用的 no hash,
参照;NoOpPasswordEncoder
这次使用 BCryptPasswordEncoder

BCryptPasswordEncoder

依赖关系

// An highlighted block
var foo = 'bar';

实装

@Configuration
@EnableWebSecurity
public class SecurityConfig : WebSecurityConfigurerAdapter() {
  @Autowired
    private UserDetailsService userDetailService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    
	@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // JDBC Type
        auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder);
    }
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(14); //指定4-31位的长度
    }
}

DB中只要保存,经过类似下面编码之后的password就可以了。

String password = "123";
String digest = passwordEncoder.encode(password);
// →→→→ $2a$14$8P.uUqQYoB0.ivT.exavCemuBh.T4UqBI0zP233ziVAvzugVh9kaO

BCrypt格式

→→→→ $2a$14$8P.uUqQYoB0.ivT.exavCemuBh.T4UqBI0zP233ziVAvzugVh9kaO

位置 内容 意义
1 ~3文字 $2a bcrypt版本号
4 ~6文字 $14 hash计算的反复回数 2^14=16384回
7 ~29文字 $8P.uUqQYoB0.ivT.exavCe salt值
30 ~最后 muBh.T4UqBI0zP233ziVAvzugVh9kaO 密码的本体

猜你喜欢

转载自blog.csdn.net/oblily/article/details/87866756