实现原理参考:

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

 

第一步: maven工程加入依赖  

<dependency>
            <groupId>com.warrenstrange</groupId>
            <artifactId>googleauth</artifactId>
            <version>1.4.0</version>
   </dependency>

 

第二步:web 端绑定谷歌

 

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

接口代码片段

    @RequestMapping(value = "/geSecretKey.do")
    @ResponseBody
    public ResponseData<Object> 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验证器关系

 

 

 

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

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

 

第三步:登录验证

 

1.账号密码验证

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

 

 

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐