原创首发
阳光沙滩博客系统-集成SpringSecurity和密码加密

添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
添加配置,放行所有请求
/**
* 安全配置类
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//所有都放行
http.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and().csrf().disable();
}
}
密码加密
public class TestPasswordEncoder {
public static void main(String[] args) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encode = passwordEncoder.encode("123456");
//数据库密文是这些里面的其中一个
//$2a$10$lJDsz8QaL2B5o4M86bThgOtGG91O1lKWjVAv3eKPCPIUSOP5DfH/m
//$2a$10$QcN8TVOwav4Kyuq5UCOhaO9jXR5eyu52AOr1sF33WL2CI0fRHzjiq
//$2a$10$fU/OAJl5EzzprWwOlid/meglkI5Wh4VCKeJ5YSL40.rX8K38nLZYG
//$2a$10$Ynr9ip7D5thxJSTcizRmXe5vqTAskB2qDSvlaa0OOpgsl6lOKskNK
System.out.println("encode == > " + encode.length());
//验证登录流程
//1、用户提交密码:123456
//2、跟数据库中的密文进行比较,如果判断提交的密码是否正确
String originalPassword = "123456";
boolean matches = passwordEncoder.matches(originalPassword, "$2a$10$Ynr9ip7D5thxJSTcizRmXe5vqTAskB2qDSvlaa0OOpgsl6lOKskNK");
System.out.println("密码是否正确 === > " + matches);
}
}
实际使用,最好在application里创建一个bean,放到容器里
@Bean
public BCryptPasswordEncoder createPasswordEncoder() {
return new BCryptPasswordEncoder();
}
相关内容请参考课程视频,感谢同学们的支持与关注。