Thinkphp5 谷歌验证

tech2022-07-05  185

https://www.jianshu.com/p/1a674952619c

说明

谷歌双重验证,也叫谷歌身份验证器、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即可

 

最新回复(0)