Thinkphp5 谷歌验证

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
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值