search
HomePHP FrameworkLaravelHow 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

  1. Install Laravel
  2. Install the QR code generatorQrCode, 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();
}

Here is a specific practical example:

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]);
}

Related tutorials:

laravel video tutorial

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!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Using Laravel: Streamlining Web Development with PHPUsing Laravel: Streamlining Web Development with PHPApr 19, 2025 am 12:18 AM

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

Laravel: An Introduction to the PHP Web FrameworkLaravel: An Introduction to the PHP Web FrameworkApr 19, 2025 am 12:15 AM

Laravel is a modern PHP framework that provides a powerful tool set, simplifies development processes and improves maintainability and scalability of code. 1) EloquentORM simplifies database operations; 2) Blade template engine makes front-end development intuitive; 3) Artisan command line tools improve development efficiency; 4) Performance optimization includes using EagerLoading, caching mechanism, following MVC architecture, queue processing and writing test cases.

Laravel: MVC Architecture and Best PracticesLaravel: MVC Architecture and Best PracticesApr 19, 2025 am 12:13 AM

Laravel's MVC architecture improves the structure and maintainability of the code through models, views, and controllers for separation of data logic, presentation and business processing. 1) The model processes data, 2) The view is responsible for display, 3) The controller processes user input and business logic. This architecture allows developers to focus on business logic and avoid falling into the quagmire of code.

Laravel: Key Features and Advantages ExplainedLaravel: Key Features and Advantages ExplainedApr 19, 2025 am 12:12 AM

Laravel is a PHP framework based on MVC architecture, with concise syntax, powerful command line tools, convenient data operation and flexible template engine. 1. Elegant syntax and easy-to-use API make development quick and easy to use. 2. Artisan command line tool simplifies code generation and database management. 3.EloquentORM makes data operation intuitive and simple. 4. The Blade template engine supports advanced view logic.

Building Backend with Laravel: A GuideBuilding Backend with Laravel: A GuideApr 19, 2025 am 12:02 AM

Laravel is suitable for building backend services because it provides elegant syntax, rich functionality and strong community support. 1) Laravel is based on the MVC architecture, simplifying the development process. 2) It contains EloquentORM, optimizes database operations. 3) Laravel's ecosystem provides tools such as Artisan, Blade and routing systems to improve development efficiency.

Laravel framework skills sharingLaravel framework skills sharingApr 18, 2025 pm 01:12 PM

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

The difference between laravel and thinkphpThe difference between laravel and thinkphpApr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

Laravel user login function listLaravel user login function listApr 18, 2025 pm 01:06 PM

Building user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.