本文作者:陳進堅
博客地址:https://jian1098.github.io
CSDN博客:https://blog.csdn.net/c_jian
聯繫方式:[email protected]
說明
谷歌雙重驗證,也叫谷歌身份驗證器、GA驗證碼,是網站用來防止暴力破解的一種手段,與短信驗證碼功能類似。
本文使用Thinkphp5框架,其他版本框架的使用方法類似。一般情況下應該給每個用戶生成各自的身份驗證碼。
下載類文件
將github
上的項目下載,然後將PHPGangsta
目錄複製到Thinkphp5
框架的extend
目錄下
https://github.com/PHPGangsta/GoogleAuthenticator
引入類文件
由於下載的文件代碼裏沒有使用命名空間,所以可以使用Thinkphp5
自帶的Loader
引入文件
<?php
namespace app\admin\controller;
use think\Controller;
use think\Loader;
class Google extends Controller
{
public function index(){
Loader::import('PHPGangsta.GoogleAuthenticator',EXTEND_PATH);
$ga = new \PHPGangsta_GoogleAuthenticator();
}
}
生成密鑰
public function index(){
Loader::import('PHPGangsta.GoogleAuthenticator',EXTEND_PATH);
$ga = new \PHPGangsta_GoogleAuthenticator();
$secret = $ga->createSecret();
echo "Secret is: ".$secret."\n\n";
}
執行結果:
Secret is: O3DAUGDNGAGZINSQ
生成二維碼鏈接
getQRCodeGoogleUrl
方法中的第一個參數是顯示在手機上的備註,可以填寫你的站點域名或者其他任意字符串,二維碼圖片尺寸可以在生成的鏈接中修改。
public function index(){
Loader::import('PHPGangsta.GoogleAuthenticator',EXTEND_PATH);
$ga = new \PHPGangsta_GoogleAuthenticator();
$secret = $ga->createSecret();
$qrCodeUrl = $ga->getQRCodeGoogleUrl('Blog', $secret);
echo "Google Charts URL for the QR-Code: ".$qrCodeUrl."\n\n";
}
執行結果:
Google Charts URL for the QR-Code: https://api.qrserver.com/v1/create-qr-code/?data=otpauth%3A%2F%2Ftotp%2FBlog%3Fsecret%3D7PUVFV7EZKH3DSWX&size=200x200&ecc=M
生成驗證碼
public function index(){
Loader::import('PHPGangsta.GoogleAuthenticator',EXTEND_PATH);
$ga = new \PHPGangsta_GoogleAuthenticator();
$secret = $ga->createSecret();
$oneCode = $ga->getCode($secret);
echo "Checking Code '$oneCode' and Secret '$secret':\n";
}
執行結果:
Checking Code '598278' and Secret '5SNJWY6656S5PMVV':
驗證驗證碼
public function index(){
Loader::import('PHPGangsta.GoogleAuthenticator',EXTEND_PATH);
$ga = new \PHPGangsta_GoogleAuthenticator();
$secret = $ga->createSecret();
$oneCode = $ga->getCode($secret);
$checkResult = $ga->verifyCode($secret, $oneCode, 2); // 2 = 2*30sec clock tolerance
if ($checkResult) {
echo 'OK';
} else {
echo 'FAILED';
}
}
執行結果:
OK
手機客戶端
安卓客戶端
可以在Google Play
搜索Google
身份驗證器或者其他安卓市場下載,比如
豌豆莢: https://www.wandoujia.com/apps/com.google.android.apps.authenticator2
百度:https://mobile.baidu.com/item?docid=1385915&source=mobres&from=1010680m
ios客戶端
在App Store
搜索 Authenticator
即可