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

# 添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
1
2
3
4

# 添加配置,放行所有请求

/**
 * 安全配置类
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //所有都放行
        http.authorizeRequests()
                .antMatchers("/**").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 密码加密

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);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

实际使用,最好在application里创建一个bean,放到容器里

@Bean
public BCryptPasswordEncoder createPasswordEncoder() {
    return new BCryptPasswordEncoder();
}
1
2
3
4

相关内容请参考课程视频,感谢同学们的支持与关注。

上次更新: 2022/03/28, 23:04:38