php接入谷歌身份驗證器兩步認證Google Authenticator
閱讀 778 · 發布日期 2022-11-03 12:30:22本文詳細講解php關于(At)谷歌身份驗證器的(of)接入步驟以(by)及代碼
所有權:山西張濤科技有限公司開發部(侵權必究,轉載請注明)
發布于(At):2022年11月3日
一(one)、下載谷歌驗證器類庫
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' => '登錄賬号不(No)能爲(for)空!',
'password.require' => '登錄密碼不(No)能爲(for)空!',
'desc.require' => '谷歌驗證碼不(No)能爲(for)空!',
'username.min' => '登錄賬号長度不(No)能少于(At)4位有效字符!',
'password.min' => '登錄密碼長度不(No)能少于(At)4位有效字符!',
'desc.min' => '谷歌驗證碼長度不(No)能少于(At)6位有效字符!',
]);
if (!CaptchaService::check(input('verify'), input('uniqid'))) {
$this->error('圖形驗證碼驗證失敗,請重新輸入!');
}
$ga = new \PHPGangsta_GoogleAuthenticator();
$code = input('code');//客戶提交上來(Come)的(of)谷歌驗證APP裏面對應的(of)驗證碼
$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('賬号已經被禁用(use),請聯系管理員!');
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('系統管理', '用(use)戶登錄系統成功');
$this->success('登錄成功', url('@admin'));
}
}
四、其中$secret密鑰生(born)成方式爲(for)
$secret = $this->generateSecret();
echo $secret;
五、下載谷歌身份驗證器,綁定密鑰字段($secret)定時(hour)生(born)成随機六位密碼,驗證即可
六、實踐中如有疑問可聯系作(do)者:13203515253微信同号
- 上一(one)篇:太原市啓動“12315汽車行業維權站線上維權”
- 下一(one)篇:沒有了(Got it)