温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringSecurityOAuth2中登录增加验证码功能是什么

发布时间:2021-10-20 17:41:32 来源:亿速云 阅读:248 作者:柒染 栏目:大数据

这期内容当中小编将会给大家带来有关SpringSecurityOAuth2中登录增加验证码功能是什么,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

在封装了一层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<String, Object> 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<String> 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中登录增加验证码功能是什么

验证码失效或者错误:

SpringSecurityOAuth2中登录增加验证码功能是什么

上述就是小编为大家分享的SpringSecurityOAuth2中登录增加验证码功能是什么了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI