使用PHP实现双因素身份验证 (2FA)
我们使用google2fa-qrcode组件(https://github.com/antonioribeiro/google2fa-qrcode)来实现:
安装google2fa-qrcode:
composer require pragmarx/google2fa-qrcode
安装bacon-qr-code,用于实现二维码显示:
composer require bacon/bacon-qr-code
使用方法:
一.在网站后台配置文件中:
<?php use PragmaRX\Google2FAQRCode\Google2FA; $google2fa = new Google2FA(); $companyName ='www.xxx.com';//一般用网站域名 $companyEmail= $username;//一般用用户名 也可用email $rt = M()->db->query("select * from twofa_config where userid=$adminid");//从数据库中读secretKey if ($rt) { $row = $rt->getRowArray(); $secretKey= $row['secretKey']; } if (empty($secretKey)) {//如果数据库中没有secretKey,则生成再存入数据库 $secretKey = $google2fa->generateSecretKey(); $keydata = array( 'secretKey'=> $secretKey, 'userid'=> $adminid, ); M()->db->table('twofa_config')->insert($keydata); } //生成二维码图 $inlineUrl = $google2fa->getQRCodeInline( $companyName, $companyEmail, $secretKey ); //附值到模板中 V()->assign([ 'qrimg'=>$inlineUrl, 'secretKey'=>$secretKey, ]); V()->display('config.html'); ?>
模板config.html:
显示二维码:
{$qrimg}
用手机下载Google Authenticator,扫描此二维码.增加帐号.
二.登录时验证
<?php use PragmaRX\Google2FAQRCode\Google2FA; $google2fa = new Google2FA(); $username = $_POST['username'];//从表单获取用户名 $rt = M()->db->query("select * from member where username='$username'"); if ($rt) { $row = $rt->getRowArray(); $adminid = $row['id']; } $rt = M()->db->query("select * from twofa_config where userid=$adminid"); if ($rt) { $row = $rt->getRowArray(); $secretKey = $row['secretKey'];//从数据库获取secretKey } $secret = $_POST['secret'];//从表单获取输入的双因素验证码:6位数字(手机上Google Authenticator显示的此帐号的6位验证码) $valid = $google2fa->verifyKey($secretKey, $secret);//对比验证 if (!$valid) { echo'{"code":0,"msg":"双因素验证码不正确"}'; exit; }else{ //验证通过 } ?>
注:使用 的是TOTP,这是一种基于时间的算法。
相关博文
使用PHP实现双因素身份验证 (2FA)