手把手教你springboot中的密码加密
1.引入Spring Security依赖
首先,需要在 pom.xml 中添加 Spring Security 依赖,因为 BCryptPasswordEncoder 是 Spring Security 提供的类:
<dependencies>
<!-- Spring Security 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
2. 配置 BCryptPasswordEncoder Bean
你需要配置一个 BCryptPasswordEncoder Bean,让 Spring 能够管理并自动注入它。我们通过配置类(通常是 @Configuration 注解的类)来实现这一点。
在一个配置类中添加:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
// 返回 BCryptPasswordEncoder 实例
return new BCryptPasswordEncoder();
}
}
• PasswordEncoder 是一个接口,BCryptPasswordEncoder 是它的实现类。
• 通过 @Bean 注解声明 BCryptPasswordEncoder,Spring 会自动创建并管理这个 Bean。
3. 在服务类中注入 PasswordEncoder
在需要对密码进行加密的地方,使用 @Autowired 注解注入 PasswordEncoder 接口。Spring 会自动将 BCryptPasswordEncoder 实现类注入到你的类中。
例如,在用户注册的业务逻辑中:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class CustomerService {
@Autowired
private PasswordEncoder passwordEncoder; // 自动注入 BCryptPasswordEncoder 实现
// 用户注册方法
public Customer registerCustomer(Customer customer) {
// 获取用户输入的原始密码
String rawPassword = customer.getPassword();
// 使用 BCryptPasswordEncoder 对密码进行加密
String encodedPassword = passwordEncoder.encode(rawPassword);
// 将加密后的密码设置到用户对象
customer.setPassword(encodedPassword);
// 保存用户信息到数据库
return customerRepository.save(customer);
}
}
代码解读:
- 自动注入 PasswordEncoder:
@Autowired 注解会自动将 SecurityConfig 中配置的 BCryptPasswordEncoder 注入到 CustomerService 类中。 - 密码加密:
o passwordEncoder.encode(rawPassword):这行代码使用 BCryptPasswordEncoder 对用户输入的原始密码进行加密,返回加密后的密码字符串。
o 加密后的密码会存储到数据库中,而不是原始密码。
4. 验证密码(登录时)
当用户登录时,你需要验证输入的密码是否与数据库中存储的加密密码匹配。你可以使用 PasswordEncoder 提供的 matches 方法来比较密码。
@Service
public class CustomerService {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private CustomerRepository customerRepository;
public boolean checkLogin(String username, String rawPassword) {
// 查找用户
Customer customer = customerRepository.findByUsername(username);
if (customer != null) {
// 使用 passwordEncoder 比较原始密码和数据库中加密后的密码
return passwordEncoder.matches(rawPassword, customer.getPassword());
}
return false;
}
}
• passwordEncoder.matches(rawPassword, storedPassword):此方法将原始密码与存储在数据库中的加密密码进行比较,返回 true 表示匹配,false 表示不匹配。
如果你在完成以上内容之后 后端运行出现以下内容,并且接口都请求不了:
Using generated security password: fdd5f264-5c8c-4937-9a27-a14873063ddc
This generated password is for development use only. Your security configuration must be updated before running your application in production.
这个是因为:
spring-boot-starter-security 是 Spring Boot 中用于集成 Spring Security 的依赖,它会为你自动配置基本的安全设置,如认证、授权、CSRF、防止表单攻击等。如果你添加了这个依赖,并且接口返回了 401 Unauthorized,可能有以下原因,与你的安全配置、认证和授权逻辑有关。
默认的 Spring Security 配置
添加 spring-boot-starter-security 后,Spring Boot 会自动启用一些默认的安全配置。例如,它会要求所有的请求都进行身份认证(默认的用户名是 user,密码是一个随机生成的密码)。如果你没有提供合适的认证信息(如用户名和密码),那么接口会返回 401 Unauthorized 错误。
解决方法————————禁用 Spring Security 默认身份验证的方法:
你可以通过创建的SecurityConfig配置类中添加以下代码,禁用 Spring Security 的默认身份验证。(Spring Boot 3.3.4 我的spring-boot是这个版本对应适配的Spring Security)
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.anyRequest().permitAll() // 允许所有请求,无需身份认证
)
.csrf(csrf -> csrf.disable()); // 禁用 CSRF 防护(如果需要)
return http.build();
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具