


How to implement google-authenticator--Google QR code validator in Laravel
This article mainly talks about using Laravel to implement Google QR code validator. It has certain reference value. I hope interested friends can learn about it.
Preparation before development
- Install Laravel
- Install the QR code generator
QrCode
, you can do it without installing it, it will be installed next
Install the expansion package
1. Run the following code to install the expansion package:
1 composer require "earnp/laravel-google-authenticator:dev-master" 2 ### 安装二维码生成器 3 ### 若composer require不到文件自行github 下载源码放入vendor相应的目录下 4 composer require simplesoftwareio/simple-qrcode 1.3.*
2. Wait for the download and installation to complete. You need to install it in config/app.php
Register the service provider and register the corresponding facade at the same time:
'providers' => [ //........ Earnp\GoogleAuthenticator\GoogleAuthenticatorServiceprovider::class, SimpleSoftwareIO\QrCode\QrCodeServiceProvider::class, ], 'aliases' => [ //.......... 'Google' => Earnp\GoogleAuthenticator\Facades\GoogleAuthenticator::class, 'QrCode' => SimpleSoftwareIO\QrCode\Facades\QrCode::class ],
3. After service injection, if you want to use custom configuration, you can also publish the configuration file to the config/views directory:
1 ###这一步可以不执行:视情况而定 2 php artisan vendor:publish
Use one (used in the project)
The usage method is very simple, mainly to generate verification code and verify verification code
1, production verification code
Production verification Use CreateSecret
for the code. You need to generate a QR code from its content for scanning by the mobile APP. The specific content has been successfully configured in google.blade.php
public function addUser(Request $request) { if($request->isMethod('get')){ // 创建谷歌验证码 $createSecret = GoogleAuthenticator::CreateSecret(); //$createSecret = [ // "secret" => "NJURUPQN6XNYGSF2" // "codeurl" => "otpauth://totp/?secret=NJURUPQN6XNYGSF2" //] // 生成二维码 $createSecret["qrcode"] = QrCode::encoding('UTF-8')->size(180)->margin(1)->generate($createSecret["codeurl"]); //发送页面 return view('auth.auth.add',['google'=>$createSecret]); } //获取数据 $user_from = $request->only(['role_id','username','pass','pass_confirmation','real_name','mobile','secret']); //保存入库 secret会存入数据库 $auth_user = new AuthUserService(); $res = $auth_user->addUser($user_from); return redirect('admin/auth/index'); }
2. Verification verification code
//登录验证 public function login(array $param) { $model = new AuthUserModel(); //Google 验证 if(!GoogleAuthenticator::CheckCode($userInfo['secret'],$param['secret'])){ return ['status'=>false,'msg'=>['secret'=>['验证码错误,请重新输入']]]; } $update = $model->editLoginInfo($userInfo['id'], $update); if(!$update){ return ['status'=>false,'msg'=>['username'=>'更新登录信息失败']]; }else{ return ['status'=>true,'data'=>$userInfo]; } }
Use two (Demo)
1 , Verification verification code
Verification verification code is generally used for binding. In login authentication, use the CheckCode
method. You need to pass in secrect
and onecode
is the verification code that can be verified. The first one is secrect
; return true
or false
##
if(Google::CheckCode($google,$request->onecode)) { // 绑定场景:绑定成功,向数据库插入google参数,跳转到登录界面让用户登录 // 登录认证场景:认证成功,执行认证操作 dd("认证成功"); }else { // 绑定场景:认证失败,返回重新绑定,刷新新的二维码 return back()->with('msg','请正确输入手机上google验证码 !')->withInput(); // 登录认证场景:认证失败,返回重新绑定,刷新新的二维码 return back()->with('msg','验证码错误,请输入正确的验证码 !')->withInput(); }
use Google; if ($request->isMethod('post')) { if (empty($request->onecode) && strlen($request->onecode) != 6) return back()->with('msg','请正确输入手机上google验证码 !')->withInput(); // google密钥,绑定的时候为生成的密钥;如果是绑定后登录,从数据库取以前绑定的密钥 $google = $request->google; // 验证验证码和密钥是否相同 if(Google::CheckCode($google,$request->onecode)) { // 绑定场景:绑定成功,向数据库插入google参数,跳转到登录界面让用户登录 // 登录认证场景:认证成功,执行认证操作 dd("认证成功"); }else { // 绑定场景:认证失败,返回重新绑定,刷新新的二维码 return back()->with('msg','请正确输入手机上google验证码 !')->withInput(); // 登录认证场景:认证失败,返回重新绑定,刷新新的二维码 return back()->with('msg','验证码错误,请输入正确的验证码 !')->withInput(); } }else { // 创建谷歌验证码 $createSecret = Google::CreateSecret(); // 您自定义的参数,随表单返回 $parameter = [["name"=>"usename","value"=>"123"]]; return view('login.google.google', ['createSecret' => $createSecret,"parameter" => $parameter]); }
The above is the detailed content of How to implement google-authenticator--Google QR code validator in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP and Flutter are popular technologies for mobile development. Flutter excels in cross-platform capabilities, performance and user interface, and is suitable for applications that require high performance, cross-platform and customized UI. PHP is suitable for server-side applications with lower performance and not cross-platform.

Database operations in PHP are simplified using ORM, which maps objects into relational databases. EloquentORM in Laravel allows you to interact with the database using object-oriented syntax. You can use ORM by defining model classes, using Eloquent methods, or building a blog system in practice.

PHP unit testing tool analysis: PHPUnit: suitable for large projects, provides comprehensive functionality and is easy to install, but may be verbose and slow. PHPUnitWrapper: suitable for small projects, easy to use, optimized for Lumen/Laravel, but has limited functionality, does not provide code coverage analysis, and has limited community support.

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

PHP Unit and Integration Testing Guide Unit Testing: Focus on a single unit of code or function and use PHPUnit to create test case classes for verification. Integration testing: Pay attention to how multiple code units work together, and use PHPUnit's setUp() and tearDown() methods to set up and clean up the test environment. Practical case: Use PHPUnit to perform unit and integration testing in Laravel applications, including creating databases, starting servers, and writing test code.

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.
