Java web接入google身份验证器二次验证

实现原理参考:

 https://blog.seetee.me/post/2011/google-two-step-verification/

 

第一步: maven工程加入依赖  


            com.warrenstrange
            googleauth
            1.4.0
  

 

第二步:web 端绑定谷歌

 

(1)点击绑定生成密钥和二维码

接口代码片段

    @RequestMapping(value = "/geSecretKey.do")
    @ResponseBody
    public ResponseData geSecretKey(HttpServletRequest request) {
        String key = GoogleAuthUtil.generateSecretKey();
        String qcodeUrl = GoogleAuthUtil.getQcode(user.getEmail(), key);
        responseData.put("key", key);
        responseData.put("qcodeUrl", qcodeUrl);
         return responseData;
    }

 

工具类:

public class GoogleAuthUtil {

    private static String googleChartUrl = ConfigProperties.getInstance()
            .getValue("google.chart.url", "https://chart.googleapis.com/chart");
    

    /**
     * Generate a random secret key. This must be saved by the server and
     * associated with the users account to verify the code displayed by Google
     * Authenticator. The user must register this secret on their device.
     * 生成一个随机秘钥
     * 
     * @return secret key
     */
    public static String generateSecretKey() {
        GoogleAuthenticator gAuth  = new GoogleAuthenticator();
        final GoogleAuthenticatorKey key = gAuth .createCredentials();
        String keyStr = key.getKey();
        return keyStr;
    }

    public static String getQcode(String email,String secret) {

        String url = googleChartUrl
                + "?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/"+ email + "%3Fsecret%3D" + secret;

        return url;

    }

    public static boolean check_code(String secret, int code) {
        GoogleAuthenticator gAuth = new GoogleAuthenticator();
        boolean isCodeValid = gAuth.authorize(secret, code);
        return isCodeValid;
    }
    

}

(2) 绑定用户和google验证器关系

 

Java web接入google身份验证器二次验证_第1张图片

 

 

点击保存,验证安装在手机上google验证器生成的验证码。后台验证逻辑,获得前端输入的code,后端进行验证代码片段如下:

boolean ret = GoogleAuthUtil.check_code(key, Integer.valueOf(code));

 

第三步:登录验证

 

1.账号密码验证

Java web接入google身份验证器二次验证_第2张图片

2.google验证器二次验证(账号密码登录验证成功后,才会二次验证)

Java web接入google身份验证器二次验证_第3张图片

 

 

 

你可能感兴趣的:(java,经验分享,安全,spring)