示意图
添加谷歌验证首先需要
构建一个自己的登录系统
安装扩展
composer require "earnp/laravel-google-authenticator:dev-master"
### 安装二维码生成器
composer require simplesoftwareio/simple-qrcode 1.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
该命令会创建视图文件
这里我将两个内容分开
一个用户显示步骤, 一个用户显示操作
使用
修改html页面
resources/views/admin/login.blade.php
将图形验证码html修改为以下代码
// 替换图形验证码
<div class="form-group has-feedback {!! !$errors->has('googlecode') ?: 'has-error' !!}">
@if($errors->has('googlecode'))
@foreach($errors->get('googlecode') as $message)
<label class="control-label" for="inputError"><i class="fa fa-times-circle-o"></i>{{$message}}</label><br>
@endforeach
@endif
<input type="text" class="form-control" placeholder="谷歌验证码" name="googlecode" value="{{ old('googlecode') }}">
<span class="glyphicon glyphicon-tags form-control-feedback"></span>
</div>
将login/google/google.blade.php
中的表单提交视图修改为
<form action="{{ empty(Config::get('google.authenticatorurl')) ? URL::current() : Config::get('google.authenticatorurl') }}"
method="POST">
{!! csrf_field() !!}
<input name="onecode" type="text" class="verificationcode" placeholder="请输入扫描后手机显示的6位验证码"
value="{{ old('onecode') }}"/>
<div>后台账号 :
<select id="parent" name="select">
@foreach($parameter as $parame)
<option value="{{$parame['id']}}">{{$parame['name']}}</option>
@endforeach
</select>
</div>
<input type="hidden" name="google" value="{{ $createSecret['secret'] }}"/>
<br/>
<button class="submit-button">立即绑定</button>
@if(Session::has('msg'))
<div class="notice">{{ Session::get('msg') }}</div>
@endif
</form>
设置路由
Route::get('googleauth', 'Web\GoogleAuthController@index');
Route::post('googleauth', 'Web\GoogleAuthController@doadd');
后端
<?php
namespace App\Http\Controllers\Web;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use Earnp\GoogleAuthenticator\GoogleAuthenticator;
use Illuminate\Http\Request;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
class GoogleAuthController extends Controller
{
public function index()
{
// 创建谷歌验证码
$createSecret = GoogleAuthenticator::CreateSecret();
// 您自定义的参数,随表单返回
$admins = Admin::get();
$parameter = $admins;
return view('login.google.google', ['createSecret' => $createSecret, "parameter" => $parameter]);
}
public function doadd(Request $request)
{
$admininfo = Admin::find($request->select);
if (empty($admininfo)) {
return back()->with('msg', '绑定账号有误 !')->withInput();
}
if ($request->isMethod('post')) {
if (empty($request->onecode) && strlen($request->onecode) != 6) return back()->with('msg', '请正确输入手机上google验证码 !')->withInput();
// google密钥,绑定的时候为生成的密钥;如果是绑定后登录,从数据库取以前绑定的密钥
$google = $request->google;
// 验证验证码和密钥是否相同
if (GoogleAuthenticator::CheckCode($google, $request->onecode)) {
// 绑定场景:绑定成功,向数据库插入google参数,跳转到登录界面让用户登录
$admininfo->google_code = $google;
$admininfo->save();
// 登录认证场景:认证成功,执行认证操作
return back()->with('msg', '验证成功 !')->withInput();
} else {
// 绑定场景:认证失败,返回重新绑定,刷新新的二维码
return back()->with('msg', '请正确输入手机上google验证码 !')->withInput();
// 登录认证场景:认证失败,返回重新绑定,刷新新的二维码
// return back()->with('msg', '验证码错误,请输入正确的验证码 !')->withInput();
}
}
return back()->with('msg', '什么操作能到我这儿 !')->withInput();
}
}
在自定义的登录页修改为如下
<?php
namespace App\Admin\Controllers;
use App\Models\Admin;
use Earnp\GoogleAuthenticator\GoogleAuthenticator;
use Encore\Admin\Controllers\AuthController as BaseAuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
class AuthController extends BaseAuthController
{
public function getLogin()
{
if (!Auth::guard('admin')->guest()) {
return redirect(config('admin.route.prefix'));
}
return view('admin.login');
}
public function postLogin(Request $request)
{
$credentials = $request->only(['username', 'password', 'googlecode']);
$validator = Validator::make($credentials, [
'username' => 'required|exists:admin_users,username',
'password' => 'required',
'googlecode' => 'required'
]);
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
}
$admininfo = Admin::where('username', $credentials['username'])->get()[0];
if (!GoogleAuthenticator::CheckCode($admininfo->google_code, $credentials['googlecode'])) {
// 登录认证场景:认证失败,返回重新绑定,刷新新的二维码
return Redirect::back()->withInput()->withErrors(['googlecode' => '谷歌验证码有误']);
}
unset($credentials['googlecode']);
if (Auth::guard('admin')->attempt($credentials)) {
admin_toastr(trans('admin.login_successful'));
return redirect()->intended(config('admin.route.prefix'));
}
return Redirect::back()->withInput()->withErrors(['username' => $this->getFailedLoginMessage()]);
}
protected function getFailedLoginMessage()
{
return Lang::has('auth.failed')
? trans('auth.failed')
: 'These credentials do not match our records.';
}
}
这里的 $admininfo->google_code
指的是 admin_users
表中添加一个 google_code
字段, 用于存储谷歌验证器的验证码.
想要修改扫码后的名称
修改 config/google.php
<?php
return [
// 中文需要UrlEncode转为utf8编码
"authenticatorname" => "修改内容(不能中文)",
"authenticatorurl" => "",
];
课外
宝塔使用laravel 生成二维码图片, 需要安装 imagick 扩展
\QrCode::format('png')->generate('hello world!!!', public_path('qrcodes/qrcode.png'));
就可生成图片