php接入谷歌身份验证器两步认证Google Authenticator
阅读 1245 · 发布日期 2022-11-03 12:30:22本文详细讲解php关于谷歌身份验证器的接入步骤以及代码
所有权:山西时代科技有限公司开发部(侵权必究,转载请注明)
发布于:2022年11月3日
一、下载谷歌验证器类库
https://github.com/chregu/GoogleAuthenticator.php
二、前端示例代码
<li class="password">
<label>
<i class="layui-icon layui-icon-password"></i>
<input class="layui-input" required pattern="^\S{4,}$" name="code" maxlength="6" type="text" autocomplete="off" placeholder="谷歌验证码" title="请输入谷歌验证码">
</label>
</li>
三、后端示例代码
public function index()
{
if (Request::isGet()) {
if (NodeService::islogin()) {
$this->redirect('@admin');
} else {
$this->title = '系统登录';
$this->domain = Request::host(true);
if (!($this->loginskey = session('loginskey'))) session('loginskey', $this->loginskey = uniqid());
$this->devmode = in_array($this->domain, ['127.0.0.1', 'localhost']) || is_numeric(stripos($this->domain, 'thinkadmin.top'));
$this->captcha = new CaptchaService();
$this->fetch();
}
} else {
$data = $this->_input([
'username' => input('username'), 'password' => input('password'),
'desc' => input('code'),
], [
'username' => 'require|min:4', 'password' => 'require|min:4','desc' => 'require|min:6',
], [
'username.require' => '登录账号不能为空!',
'password.require' => '登录密码不能为空!',
'desc.require' => '谷歌验证码不能为空!',
'username.min' => '登录账号长度不能少于4位有效字符!',
'password.min' => '登录密码长度不能少于4位有效字符!',
'desc.min' => '谷歌验证码长度不能少于6位有效字符!',
]);
if (!CaptchaService::check(input('verify'), input('uniqid'))) {
$this->error('图形验证码验证失败,请重新输入!');
}
$ga = new \PHPGangsta_GoogleAuthenticator();
$code = input('code');//客户提交上来的谷歌验证APP里面对应的验证码
$secret = '2DSCSLVDRZNLIMWU';
$checkResult = $ga->verifyCode($secret, $code, 1);
$map = ['is_deleted' => '0', 'username' => $data['username']];
$user = Db::name('SystemUser')->where($map)->order('id desc')->find();
if (empty($user)) $this->error('登录账号或密码错误,请重新输入!');
if (md5($user['password'] . session('loginskey')) !== $data['password']) {
$this->error('登录账号或密码错误,请重新输入!');
}
if (!$checkResult) {
$this->error('谷歌验证码错误,请重新输入!');
}
if (empty($user['status'])) $this->error('账号已经被禁用,请联系管理员!');
Db::name('SystemUser')->where(['id' => $user['id']])->update([
'login_at' => Db::raw('now()'), 'login_ip' => Request::ip(), 'login_num' => Db::raw('login_num+1'),
]);
session('loginskey', null);
session('admin_user', $user);
cookie('loginskey', null);
cookie('admin_user', $user);
NodeService::applyUserAuth(true);
sysoplog('系统管理', '用户登录系统成功');
$this->success('登录成功', url('@admin'));
}
}
四、其中$secret密钥生成方式为
$secret = $this->generateSecret();
echo $secret;
五、下载谷歌身份验证器,绑定密钥字段($secret)定时生成随机六位密码,验证即可
六、实践中如有疑问可联系作者:13203515253微信同号
- 上一篇:太原市启动“12315汽车行业维权站线上维权”
- 下一篇:没有了