亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
Install Required Packages
Add Columns to Users Table
Update User Model
Generate and Display QR Code
Verify and Enable 2FA
Enforce 2FA During Login
Disable 2FA Option
首頁 php框架 Laravel 如何在 Laravel 中實現(xiàn)雙因素身份驗證(2FA)?

如何在 Laravel 中實現(xiàn)雙因素身份驗證(2FA)?

Oct 16, 2025 am 11:11 AM

使用pragmarx/google2fa-laravel實現(xiàn)Laravel雙因素認(rèn)證:安裝包後添加兩字段到users表,生成TOTP密鑰並顯示QR碼供掃描,驗證一次性密碼後啟用2FA,登錄時若開啟2FA則跳轉(zhuǎn)至驗證碼輸入頁,校驗通過後登錄,支持用戶輸入密碼後關(guān)閉2FA功能。

How to implement two-factor authentication (2FA) in Laravel?

To implement two-factor authentication (2FA) in Laravel, you can use packages like Google2FA or Laravel Fortify with laravel/fortify and pragmarx/google2fa-laravel . Below is a step-by-step guide using pragmarx/google2fa-laravel for TOTP-based 2FA.

Install Required Packages

Add the Google2FA package via Composer:

composer require pragmarx/google2fa-laravel

This package provides integration with Google Authenticator apps (like Google Authenticator, Authy, etc.).

Add Columns to Users Table

Create a migration to add 2FA-related fields to your users table:

php artisan make:migration add_two_factor_columns_to_users_table --table=users

In the migration file:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->boolean('two_factor_enabled')->default(false);
        $table->string('two_factor_secret')->nullable();
    });
}

Run the migration:

php artisan migrate

Update User Model

Add the necessary attributes to your User model:

protected $fillable = [
    'name',
    'email',
    'password',
    'two_factor_secret',
    'two_factor_enabled',
];

protected $hidden = [
    'two_factor_secret',
];

You may also cast the secret if needed, though it's usually stored encrypted.

Generate and Display QR Code

Create a controller method to generate a 2FA secret and show the QR code:

use PragmaRX\Google2FA\Google2FA;

class TwoFactorController extends Controller
{
    public function show()
    {
        $google2fa = app('pragmarx.google2fa');

        $secret = $google2fa->generateSecretKey();

        // Store in session temporarily
        session(['2fa_secret' => $secret]);

        $QRImage = $google2fa->getQRCodeInline(
            config('app.name'),
            auth()->user()->email,
            $secret
        );

        return view('auth.two-factor-setup', compact('QRImage', 'secret'));
    }
}

In your Blade view ( two-factor-setup.blade.php ):

<div>
    <p>Scan the QR code with Google Authenticator.</p>
    <div>{!! $QRImage !!}</div>
    <p>Or enter this key manually: <strong>{{ $secret }}</strong></p>
</div>

@csrf

Verify and Enable 2FA

Create a method to verify the one-time password and enable 2FA:

use PragmaRX\Google2FA\Exceptions\IncompatibleWithGoogleAuthenticatorException;
use PragmaRX\Google2FA\Exceptions\InvalidCharactersException;
use PragmaRX\Google2FA\Exceptions\SecretKeyTooShortException;

public function enable(Request $request)
{
    $request->validate(['one_time_password' => 'required']);

    $google2fa = app('pragmarx.google2fa');

    $secret = $request->session()->get('2fa_secret');

    $valid = $google2fa->verifyKey($secret, $request->one_time_password);

    if ($valid) {
        auth()->user()->update([
            'two_factor_secret' => $secret,
            'two_factor_enabled' => true,
        ]);

        $request->session()->forget('2fa_secret');

        return redirect()->route('dashboard')->with('success', '2FA enabled successfully.');
    }

    return back()->withErrors(['one_time_password' => 'Invalid code.']);
}

Enforce 2FA During Login

Modify your login logic (eg, in a custom request or middleware) to check if 2FA is enabled.

After successful password authentication, if 2FA is enabled, redirect to a 2FA verification page:

// In LoginController or Fortify hook
if ($user->two_factor_enabled) {
    session(['2fa:user:id' => $user->id]);
    return redirect('/verify-2fa');
}

Create a verification form where the user enters the OTP.

Verification example:

public function verify(Request $request)
{
    $userId = $request->session()->get('2fa:user:id');

    if (!$userId) {
        return redirect('/login');
    }

    $user = User::findOrFail($userId);

    $google2fa = app('pragmarx.google2fa');

    $valid = $google2fa->verifyKey($user->two_factor_secret, $request->one_time_password);

    if ($valid) {
        $request->session()->forget('2fa:user:id');
        Auth::loginUsingId($user->id);

        return redirect()->intended('/dashboard');
    }

    return back()->withErrors(['one_time_password' => 'Invalid 2FA code.']);
}

Disable 2FA Option

Allow users to disable 2FA (after confirming password):

public function disable(Request $request)
{
    $request->validate(['password' => 'required']);

    if (!Hash::check($request->password, auth()->user()->password)) {
        return back()->withErrors(['password' => 'Invalid password.']);
    }

    auth()->user()->update([
        'two_factor_secret' => null,
        'two_factor_enabled' => false,
    ]);

    return redirect()->back()->with('success', '2FA disabled.');
}

Basically, that's how you add full 2FA support in Laravel using Google Authenticator. You can enhance it with backup codes, recovery options, or use Laravel Fortify/Spark for built-in support.

以上是如何在 Laravel 中實現(xiàn)雙因素身份驗證(2FA)?的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

如何將消息記錄到Laravel中的文件? 如何將消息記錄到Laravel中的文件? Sep 21, 2025 am 06:04 AM

LaraveluseMonologTologMessagesViathelogFacade,withDefaultLogSstoreDinstorage/logs/logaver.log.configurechannelsinconfig/loggpocontrolOlOutput; theDefeftoconTrolOutput; theDefeftStackChannAnneLagateSmultipleHersMultipleHerslikeSlikeSlikesingLikeSingLikeSingle,whatwrile.afile.usel.uselel.uselel.usecy.useleleel.use)

如何在Laravel中驗證API 如何在Laravel中驗證API Sep 18, 2025 am 12:26 AM

installlaravelsanctumviaCompoSerandPublishItsFiles,thenRunMigrations.2.AddthehasapitokenStraittheUserModel.3.definelogin,logout of lokout of anduserroutesinapi.php

如何使用Laravel的Hasmanythrough關(guān)係? 如何使用Laravel的Hasmanythrough關(guān)係? Sep 17, 2025 am 06:38 AM

AcountrycanaccessallpostSthrouserSerssinghasmanyThrough

如何使用Laravel中的路線資源控制器? 如何使用Laravel中的路線資源控制器? Sep 24, 2025 am 05:05 AM

Laravel資源控制器通過RESTful路由快速處理CRUD操作,使用Artisan命令生成控制器並註冊資源路由,單行代碼即可創(chuàng)建全部標(biāo)準(zhǔn)路由,支持限制動作、添加中間件及命名,結(jié)合路由模型綁定可自動解析參數(shù),提升開發(fā)效率並保持代碼結(jié)構(gòu)清晰。

如何使用Laravel Sanctum實施API身份驗證? 如何使用Laravel Sanctum實施API身份驗證? Sep 19, 2025 am 04:08 AM

toimplementApiAthenticationWithlaravelsanctum,YouneEdtoStepoken的authenticationthatallowsspas,mobileApps,andth-thired-thired-partyservicestoseStoseStoSecerlelyAccessyourapi.sanctumprovidesleightigeslightightightwerightightweightightweightightappablebybybybybybyissugyapitokensthatcanthatcan

如何在Laravel控制器中重定向用戶? 如何在Laravel控制器中重定向用戶? Sep 21, 2025 am 05:26 AM

使用redirect()輔助函數(shù)可實現(xiàn)Laravel控制器中的重定向,如redirect()->route('home')跳轉(zhuǎn)到命名路由,redirect('/dashboard')跳轉(zhuǎn)到指定URL,redirect()->back()返回上一頁,結(jié)合withInput()保留表單數(shù)據(jù),with()傳遞會話消息,推薦使用命名路由以提高可維護(hù)性。

如何在Laravel編寫RAW SQL查詢? 如何在Laravel編寫RAW SQL查詢? Sep 24, 2025 am 02:55 AM

使用DB門面執(zhí)行原生SQL,根據(jù)查詢類型選擇DB::select、DB::insert、DB::update或DB::delete,並用參數(shù)綁定防止SQL注入;結(jié)構(gòu)變更可用DB::unprepared;結(jié)合DB::raw可在查詢構(gòu)造器中嵌入原生表達(dá)式。

如何連接到Laravel的第二個數(shù)據(jù)庫? 如何連接到Laravel的第二個數(shù)據(jù)庫? Sep 17, 2025 am 01:42 AM

配置第二個數(shù)據(jù)庫連接:在config/database.php中添加新連接並設(shè)置.env變量;2.使用DB::connection('mysql_second')或模型$connection屬性指定連接;3.運(yùn)行時可用on()方法動態(tài)切換;4.遷移時用Schema::connection()並配合--database選項執(zhí)行。

See all articles