Authentication service---Integrate SMS verification code, user registration and login, and password is stored with MD5 encryption [2]

Three in a row

foreword

Add login and registration to the distributed microservice system (the record of user login information in the distributed case has not been completed yet), the main record: a microservice is dedicated to managing user information. It is necessary to complete the user registration and login process in the form of remote calling, and at the same time, the password is encrypted in MD5 and saved to the database.

1. Registration

1.1 General process

  • 1. The user fills in the basic information
  • 2. The user clicks to obtain the verification code
    • 1) Call the written third-party service, which has an interface obtained by Alibaba Cloud SMS verification.
    • 2) Aliyun SMS verification sends the verification code to the mobile phone (the verification code is generated and set by itself)
  • 3. After the user fills in the verification code, click Register
    • 1) The background checks the input information and verification
    • 2) The verification of the verification code is done through redis. First, store the generated verification code in an expirable key. When registering, compare the verification code entered by the user with the verification code taken from redis
    • 3) Encrypt the input plaintext password through MD5
  • 4. Remotely call the interface for adding user information to complete the registration operation. The management of user information is written separately as a microservice.

1.2 Core code

Realization of specific business logic in the remote service interface

    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVo vos, BindingResult result,
                           RedirectAttributes attributes) {
    
    

        //如果有错误回到注册页面
        if (result.hasErrors()) {
    
    
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors",errors);

            //效验出错回到注册页面
            return "redirect:http://auth.zyz.com/reg.html";
        }

        //1、效验验证码
        String code = vos.getCode();

        //获取存入Redis里的验证码
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
        if (!StringUtils.isEmpty(redisCode)) {
    
    
            //截取字符串
            if (code.equals(redisCode.split("_")[0])) {
    
    
                //删除验证码;令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+vos.getPhone());
                //验证码通过,真正注册,调用远程服务进行注册
                R register = memberFeignService.register(vos);
                if (register.getCode() == 0) {
    
    
                    //成功
                    return "redirect:http://auth.zyz.com/login.html";
                } else {
    
    
                    //失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", register.getData("msg",new TypeReference<String>(){
    
    }));
                    attributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.zyz.com/reg.html";
                }


            } else {
    
    
                //效验出错回到注册页面
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.zyz.com/reg.html";
            }
        } else {
    
    
            //效验出错回到注册页面
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.zyz.com/reg.html";
        }
    }

Remote service interface – user information registration

Call the interface for adding users through remote service calls.

    @Override
    public void register(MemberUserRegisterVo vo) {
    
    

        MemberEntity memberEntity = new MemberEntity();

        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        //设置其它的默认信息
        //检查用户名和手机号是否唯一。感知异常,异常机制
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        memberEntity.setNickname(vo.getUserName());
        memberEntity.setUsername(vo.getUserName());
        //密码进行MD5加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setGender(0);
        memberEntity.setCreateTime(new Date());

        //保存数据
        this.baseMapper.insert(memberEntity);
    }

1.3 Page effect

insert image description here

2. Login

2.1 General login process

  • 1. The user enters the account number | mobile phone number and password. log in
  • 2. Remote service call interface to query user login information

2.2 Core code

    @PostMapping(value = "/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session) {
    
    

        //远程登录
        R login = memberFeignService.login(vo);

        if (login.getCode() == 0) {
    
    
            MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {
    
    });
            session.setAttribute(LOGIN_USER,data);
            return "redirect:http://zyz.com";
        } else {
    
    
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){
    
    }));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.zyz.com/login.html";
        }
    }

remote service interface

Remote service call, calling the interface of another service

    @Override
    public MemberEntity login(MemberUserLoginVo vo) {
    
    

        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        //1、去数据库查询 SELECT * FROM ums_member WHERE username = ? OR mobile = ?
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginacct).or().eq("mobile", loginacct));

        if (memberEntity == null) {
    
    
            //登录失败
            return null;
        } else {
    
    
            //获取到数据库里的password
            String password1 = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //进行密码匹配
            boolean matches = passwordEncoder.matches(password, password1);
            if (matches) {
    
    
                //登录成功
                return memberEntity;
            }
        }

        return null;
    }

2.3 Page effect

insert image description here

3. Database saves data

insert image description here

Guess you like

Origin blog.csdn.net/weixin_43304253/article/details/130049002