Spring Security BCryptPasswordEncoder 密码加盐

Spring Security BCryptPasswordEncoder 密码加盐

引入spring-boot-starter-security 的Jar包

  •     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    

使用 BCryptPasswordEncoder 对密码加盐加密

  • 测试类

    •         //region Description
              BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
              for (int i = 0; i < 10; i++) {
             
             
                  String admin = bCryptPasswordEncoder.encode("admin");
                  System.out.println(admin);
              }
              // 从上面的输出中随便拿一个
              System.out.println(bCryptPasswordEncoder.matches("admin",    "$2a$10$U96JT2Wzq/0w1D9XBUsXQ.s7AHgruQayc3ay2oqYkGJyJb1vZyJ0i"));
              //endregion
      
  • 上面的运行结果

    • $2a$10$w2/bCNOlrFxx.2.JP62AC.GtCGWVHuSPqqA27tcR1DxseKRebiU2G
      $2a$10$U96JT2Wzq/0w1D9XBUsXQ.s7AHgruQayc3ay2oqYkGJyJb1vZyJ0i
      $2a$10$lJTu
### Spring Boot 和 Spring Security 中实现密码加盐的最佳实践 在现代Web应用程序开发中,确保用户数据的安全至关重要。为了防止存储明文密码带来的风险,在Spring Boot和Spring Security环境中采用加密技术来处理用户密码是非常必要的。 #### 使用BCryptPasswordEncoder进行密码编码 推荐的做法是利用`BCryptPasswordEncoder`类来进行密码哈希操作并自动加入随机盐值[^1]。该方法不仅能够有效增强安全性,而且简化了开发者的工作量,因为不需要手动管理盐值的生成与保存过程: ```java import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class PasswordEncoderExample { public static void main(String[] args) { BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String rawPassword = "mySecretPassword"; String encodedPassword = passwordEncoder.encode(rawPassword); System.out.println("Encoded Password: " + encodedPassword); boolean matches = passwordEncoder.matches(rawPassword, encodedPassword); System.out.println("Does the entered password match? : " + matches); } } ``` 此代码片段展示了如何创建一个`BCryptPasswordEncoder`实例,并调用其`encode()`函数对原始字符串形式的密码执行散列运算;随后可以通过`matches()`函数验证输入的纯文本密码是否匹配已有的散列值[^2]。 #### 自定义UserDetailsService接口以支持加盐后的密码校验 当涉及到实际项目中的用户登录逻辑时,则需自定义实现`UserDetailsServiceImpl`服务层组件,以便加载数据库中存在的经过BCrypt算法处理过的密文以及相应的用户名信息返回给框架用于后续的身份验证流程[^3]。 ```java @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { AppUser appUser = userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found")); return new org.springframework.security.core.userdetails.User(appUser.getUsername(), appUser.getPassword(), true, true, true, true, getAuthorities()); } private Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> authList = new ArrayList<>(); // Add roles or permissions here as needed. return authList; } } ``` 上述例子说明了一个简单的基于JPA仓库模式获取用户的场景,其中包含了从持久化层读取到内存对象转换的过程,最终形成符合Spring Security预期的数据结构供内部使用。 #### 配置SecurityConfig类启用密码编码器 最后一步是在全局配置文件里指定所使用的密码编解码工具,这通常是在继承自`WebSecurityConfigurerAdapter`抽象基类的应用程序特定设置类完成的。这里展示了一种方式来注册前面提到的`BCryptPasswordEncoder`作为默认处理器: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder getPasswordEncoder(){ return new BCryptPasswordEncoder(10); // 参数表示迭代次数,默认为10次 } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()).passwordEncoder(getPasswordEncoder()); } } ``` 这段Java配置表明了怎样通过Spring容器注入的方式让整个应用范围内都能识别到这个强类型的工厂bean,从而保证每次涉及身份验证环节都会运用相同的策略去比较提交过来的新旧两版凭证材料之间的关系。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BinBin_Bang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值