form1.cn
Make a little progress every day

php使用谷歌验证 (Google Authenticator) 的双重身份验证

11th of April 2018 PHP PHPcode 13728

开启Google的登陆二步验证(即Google Authenticator服务)后用户登陆时需要输入额外由手机客户端生成的一次性密码。实现Google Authenticator功能需要服务器端和客户端的支持。服务器端负责密钥的生成、验证一次性密码是否正确。客户端记录密钥后生成一次性密码。


使用PHP实现方法:


这是一个程序实现的PHP调用方法,把这个clone到你本地

https://github.com/PHPGangsta/GoogleAuthenticator


你可以先看一下他的README.md文件


这个应该是phpgangsta的官网

https://www.phpgangsta.de/2-faktor-authentifizierung-mit-dem-google-authenticator


php实现代码:

<?php
require_once 'PHPGangsta/GoogleAuthenticator.php';
$ga = new PHPGangsta_GoogleAuthenticator();
$secret = $ga->createSecret();
//这是生成的密钥,每个用户唯一一个,为用户保存起来
echo $secret; echo '<br />';
//下面为生成二维码,内容是一个URI地址(otpauth://totp/账号?secret=密钥&issuer=标题)
//例子:otpauth://totp/zjwlgr@163.com?secret=6HPH5373NXGO6M7K&issuer=zjwlgr
$qrCodeUrl = $ga->getQRCodeGoogleUrl('zjwlgr@163.com', $secret, 'kuaxue');
echo "Google Charts URL for the QR-Code: ".$qrCodeUrl."\n\n";
//下面为验证参数
$oneCode = $_GET['code'];//用户手机中获取的code
$secret = '6HPH5373NXGO6M7K';//用户唯一一个密钥,上面生成的
//下面为验证用户输入的code是否正确
$checkResult = $ga->verifyCode($secret, $oneCode, 2);    // 2 = 2*30秒 时钟容差
echo '<br />';
if ($checkResult) {
    echo 'OK';
} else {
    echo 'FAILED';
}


创建二维码或密钥,添加到手机Authenticator中,用手机中得到的code与用户和密钥进行验证,就是这么几行