首先要确保项目已经引入了Spring Security的依赖,如果没有,可以在pom.xml添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
创建 BCryptPasswordEncoder
的 Bean
在配置类,添加如下代码:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
public class SecurityConfig {
/**
* 配置密码加密器
*/
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 放行接口配置
*/
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable() // 关闭 csrf(你是前后端分离项目一般要关)
.authorizeHttpRequests(auth -> auth
.requestMatchers(
"/user/login",
"/user/register",
"/swagger-ui/**",
"/v3/api-docs/**",
"/favicon.ico"
).permitAll() // 放行这些接口
.anyRequest().permitAll() // 如果你还没有登录控制,可全部放行(后期记得改为 .authenticated())
)
.formLogin().disable() // 禁用默认登录页面
.httpBasic().disable(); // 禁用 basic auth
return http.build();
}
}
然后就可以在service中注入使用
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Service
public class TeamServiceImpl implements TeamService {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
// 然后你就可以直接用:
// String encodedPassword = passwordEncoder.encode(team.getPassword());
}
需要注意的是,加密后密码是无法解密的,只能在校验时通过 passwordEncoder.matches(raw, encoded)
判断是否匹配。因此在校验加入队伍密码时也应该使用 matches
方法进行比对。
// 关键:使用 matches 方法校验
if (pwd == null || !passwordEncoder.matches(pwd, team.getPassword())) {
throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
}