java - 我的 Spring Security 项目中的 BCrypt (Spring security)
问题描述
我该怎么做加密。这样在数据库中它就不会显示用户密码。我现在保存在数据库中 - 登录名和密码,用户角色。我需要密码必须在数据库中加密(BCrypt)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/**").permitAll()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/allStudents")
.and()
.logout()
.and()
.csrf().disable();
}
@Bean
public PasswordEncoder weDoNotWantEncryption() {
return new PasswordEncoder() {
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return rawPassword.toString().equals(encodedPassword);
}
};
}
}
解决方案
非常简单 - 只需将您的weDoNotWantEncryption()
函数替换为返回 BCrypt 实例的函数:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
BCryptPasswordEncoder
实现PasswordEncoder
(顾名思义),因此已经为encode()
和定义了很好的方法matches()
。
请注意,这(当然)会使数据库中当前的任何密码都无法使用,尽管鉴于这些密码以明文形式存储,我假设(并希望/祈祷)这是在测试环境中,而不是在生产环境中。
推荐阅读
- css - 将 1 个孩子左对齐,其余的在 div 中右对齐
- c# - WPF如何使用MVVM清除列表视图中的texbox内容
- matplotlib - 为 seaborn 计数图中的所有条形应用单一颜色
- git - 实际上删除 git commit 的方式是它会从日志中消失
- angular - Angular9 中的当前用户信息
- python - 将 list 类型的 pandas 列转换为 dict
- java - 为什么子对象调用具有主方法的超类的私有方法?
- rust - 了解 rust 借用和取消引用
- node.js - 在 Sequelize 操作之后关闭我的连接是一个好习惯吗?
- swift - 如何在应用程序中读取 Localizable.strings