SpringSecurityOAuth2(6) 登录增加验证码功能

GitHub地址

码云地址

本文基于上文 SpringSecurityOAuth2(5)自定义登录登出

在封装了一层RestTemplate 请求的基础上。请求code,使用redis保存带用户名的限时缓存 例如保存60秒缓存 在登录请求验证用户名密码之前先进过code验证。

登录设置验证码,验证码有效期为1分钟,登录成功后或者到达最大时间后验证码即失效。验证码以用户名_code 的关键字保存在redis中,并设置失效时间,用户名+验证码匹配通过后才进行下一步的token生成,生成token后,即删除验证码。

改造(5)中的tokenController代码(本文只展示实现思路,code直接生成随机数了)

 @PostMapping("/login")
    public ResponseVo login(HttpServletRequest request) throws UnsupportedEncodingException {
        String header = request.getHeader("Authorization");
        if (header == null && !header.startsWith("Basic")) {
            return new ResponseVo(400, "请求头中缺少参数");
        }
        String code = request.getParameter("code");
        String username = request.getParameter("username");

        if(code==null){
            return new ResponseVo(500,"验证码缺失");
        }
        String old_code =redisTemplate.opsForValue().get(username+"_code");

        if(old_code==null){
            return new ResponseVo(500,"验证码不存在或者已经过期");
        }
        if(!code.equals(old_code)){
            return new ResponseVo(500,"验证码错误");
        }


        String url = "http://" + request.getRemoteAddr() + ":" + request.getServerPort() + "/oauth/token";

        Map map = new HashMap<>();
        map.put("grant_type", "password");
        map.put("username", username);
        map.put("password", request.getParameter("password"));

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", header);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);  // 必须该模式,不然请求端无法取到 grant_type

        HttpEntity httpEntity = new HttpEntity<>(headers);

        ResponseEntity response = restTemplate.postForEntity(url + "?" + LinkStringUtil.createLinkStringByGet(map), httpEntity, String.class);

        if (response.getStatusCodeValue() == 200) {
            return new ResponseVo(200, "登录成功", JSONObject.parseObject(response.getBody()));
        } else {
            return new ResponseVo(500, "登录失败");
        }
    }

    @PostMapping("/getCode")
    public String getCode(String username) {
        String code = String.valueOf(Math.random() * 100);
        redisTemplate.opsForValue().set(username + "_code", code, 60, TimeUnit.SECONDS);
        return "code is " + code;
    }

验证通过:

SpringSecurityOAuth2(6) 登录增加验证码功能_第1张图片

验证码失效或者错误:

SpringSecurityOAuth2(6) 登录增加验证码功能_第2张图片

转载于:https://my.oschina.net/u/3500033/blog/3083150

你可能感兴趣的:(SpringSecurityOAuth2(6) 登录增加验证码功能)