实现原理参考:
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));