PHP 登录引入双因素认证服务

双因素认证(2FA)的介绍详见文档,此处不做介绍。

引入方法

1、安装扩展

 composer require pragmarx/google2fa

GitHub 仓库

2、给用户生成秘钥

在用户信息中添加秘钥字段 google2fa_secret,在用户登录后,若该字段为空说明没有关联双因素认证,跳转关联双因素认证逻辑。

为用户生成双因素认证秘钥:

 use PragmaRX\Google2FA\Google2FA;

$google2fa = new Google2FA();

return $google2fa->generateSecretKey();

根据该秘钥和站点信息、用户信息生成二维码

 # 生成二维码内容
 $qrCodeUrl = $google2fa->getQRCodeUrl(
    $companyName, # 站点名称
    $companyEmail, # 用户名称
    $secretKey, # 上一步生成的秘钥
);

// 使用您自己的二维码生成器生成图片URL:
$google2fa_url = custom_generate_qrcode_url($qrCodeUrl);

# 将二维码展示到页面上
<img src="{{ $google2fa_url }}" alt="">

3、获取动态密码并验证

使用 Authenticator 应用程序扫描上面二维码,获取双因素验证的动态密码。

推荐的 Authenticator 应用程序:

将密码输入到站点中和秘钥一起验证合法性,验证通过则将上面秘钥保存到用户信息中,用作后续验证的秘钥使用。

 # 验证动态密码
 $auth_code =  $request->input('secret');

 $google2fa = new Google2FA();

 if($google2fa->verifyKey($user->google2fa_secret , $auth_code))# bool
 {
      # success
      # 保存用户秘钥
 } else {
      // failed
}

4、后续使用

保存了用户秘钥后,后续要登录系统或做敏感操作,可以要求输入 双因素验证的动态密码进行验证(动态密码从 Authenticator 应用程序中获取 ),验证逻辑同上面第三步,验证通过后才能做后续操作。

引用链接

[1] 文档: //wangmaolin.net/topic/%E5%AE%89%E5%85%A8/jrqvwrzy8p
[2] GitHub 仓库: https://github.com/antonioribeiro/google2fa
[3] Microsoft Authenticator: https://www.microsoft.com/en-us/security/mobile-authenticator-app
[4] Google Authenticator: https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2
[5] Aegis Authenticator: https://github.com/beemdevelopment/Aegis