谷歌二次验证 Google Authenticator

后台登录要搞令牌,类似于steam令牌、企鹅令牌等等

开启Google的登陆二步验证(即Google Authenticator服务)后用户登陆时需要输入额外由手机客户端生成的一次性密码。

实现Google Authenticator功能需要服务器端和客户端的支持。服务器端负责密钥的生成、验证一次性密码是否正确。客户端记录密钥后生成一次性密码。

流程如下

大致流程

1、运行如下代码安装拓展包:

composer require "earnp/laravel-google-authenticator:dev-master"
### 安装二维码生成器
composer require simplesoftwareio/simple-qrcode 1.3.*

3.等待下载安装完成,需要在config/app.php中注册服务提供者同时注册下相应门面:

'providers' => [
    //........
    Earnp\GoogleAuthenticator\GoogleAuthenticatorServiceprovider::class,
    SimpleSoftwareIO\QrCode\QrCodeServiceProvider::class,
],

'aliases' => [
     //..........
    'Google' => Earnp\GoogleAuthenticator\Facades\GoogleAuthenticator::class,
    'QrCode' => SimpleSoftwareIO\QrCode\Facades\QrCode::class
],

服务注入以后,如果要使用自定义的配置,还可以发布配置文件到config/views目录:

php artisan vendor:publish

注意绑定视图位置为resources/views/login/google/google.blade.php,然后您可以在config/google.php中修改账号名绑定验证地址

// 创建谷歌验证码
$createSecret = GoogleAuthenticator::CreateSecret();
//$createSecret = [
// "secret" => "NJURUPQN6XNYGSF2"
// "codeurl" => "otpauth://totp/?secret=NJURUPQN6XNYGSF2"
//]
// 生成二维码
$createSecret["qrcode"] = QrCode::enCoding('UTF-8')->size(180)->margin(1)->generate($createSecret["codeurl"]);
核心就是生成二维码之后,主要就是secret串,用手机app扫一扫就添加到验证器上面了

然后 服务端将生成的secret 串与用户进行绑定

下面是展示二维码的代码,用以进行绑定secret 串,如果绑定过就不再展示了

// 判断该用户是否已经存在google秘钥、没有重新生成
        if (empty($user['secret']) && $user['google_status'] === 0) {
            // 获取google秘钥
            $google = GoogleAuthenticator::CreateSecret();
            // 生成二维码
            $google["qrcode"] = QrCode::encoding('UTF-8')->size(180)->margin(1)->generate($google["codeurl"]);
        } else {
            $google['secret'] = $user['secret'];
            $google_url = "otpauth://totp/?secret=" . $user['secret'];
            // 生成二维码
            $google["qrcode"] = QrCode::encoding('UTF-8')->size(180)->margin(1)->generate($google_url);
        }

最后用户进行提交code,用绑定的secret 串 来校验

// 判断该用户是否开启google验证
    // 将用户输入的验证码与秘钥进行匹配
    if(1 === $user['google_status']){
        // Google验证码与秘钥进行匹配
        if(!GoogleAuthenticator::CheckCode($user['secret'],$param['secret'])){
           return '匹配成功';
        }
    }

然后可以继续登录后续业务了,如果要取消 只需要 删除user绑定的secret串就可重绑了。

猜你喜欢

转载自blog.csdn.net/qiuziqiqi/article/details/131067316