P.13-用户密码加密存储密码、P.14-铺垫知识jwt工具类使用、P.15-登录接口实现细节分析

发布时间 2023-04-25 15:41:08作者: ja不会va

P.13-用户密码加密存储密码

  实际项目中我们不会把密码明文存储在数据库中。

  默认使用的PasswordEncoder要求数据库中的密码格式为:{id}password 。它会根据id去判断密码的加密方式。

    但是我们一般不会采用这种方式。所以就需要替换PasswordEncoder。

  我们一般使用SpringSecurity为我们提供的BCryptPasswordEncoder。

  我们只需要使用把BCryptPasswordEncoder对象注入Spring容器中,SpringSecurity就会使用该PasswordEncoder来进行密码校验。

  定义一个SpringSecurity的配置类,SpringSecurity要求这个配置类要继承WebSecurityConfigurerAdapter。

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //创建BCryptPasswordEncoder注入容器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

   测试1

@SpringBootTest
public class MapperTest {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void TestBCryptPasswordEncoder(){

      BCryptPasswordEncoder BCPE = new BCryptPasswordEncoder();

        String encode = BCPE.encode("123");
        String encode1 = BCPE.encode("123");
        System.out.println(encode);
        System.out.println(encode1);
    }

  测试2

@SpringBootTest
public class MapperTest {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void TestBCryptPasswordEncoder(){

      BCryptPasswordEncoder BCPE = new BCryptPasswordEncoder();
        System.out.println(BCPE.matches("123",
                "$2a$10$ykgwUyG0nel6VwCdue0hdesAURjW1tsI7D64LQi.uw7KVf9JYWjXq"));

    }

   测试3

@SpringBootTest
public class MapperTest {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Test
    public void TestBCryptPasswordEncoder(){
        System.out.println(passwordEncoder.matches("123",
                "$2a$10$ykgwUyG0nel6VwCdue0hdesAURjW1tsI7D64LQi.uw7KVf9JYWjXq"));
    }

  为true则无问题

  我们还需要将测试一运行结合替换掉数据库内的密码字段进行替换再去运行进行测试

  这便就是将密码进行加密后再进行登录

P.14-铺垫知识jwt工具类的使用

P.15-登录接口实现细节分析

  自定义登陆接口,然后让SpringSecurity对这个接口放行,让用户访问这个接口的时候不用登录也能访问。

  在接口中我们通过AuthenticationManager的authenticate方法来进行用户认证,所以需要在SecurityConfig中配置把AuthenticationManager注入容器。

  认证成功的话要生成一个jwt,放入响应中返回。并且为了让用户下回请求时能通过jwt识别出具体的是哪个用户,我们需要把用户信息存入redis,可以把用户id作为key