Laravel9的HttpBasicAuth基本认证

Laravel9的HttpBasicAuth基本认证

本文主要记录Laravel9的HttpBasicAuth用户基本授权登录的使用,写接口时部分接口需要先登录获取token才能使用,此时我们就可以用到Laravel内置自带的HttpBasicAuth的基本认证功能。

Laravel 安装完之后执行数据迁移

执行下面命令会在数据库中创建用户表users和数据迁移版本控制表migrations

php artisan migrate

创建一个Seeder用来生成一个用户

php artisan make:seeder UserSeeder 
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert(['name'=>'fujuhao','email'=>'906855921@qq.com','password'=>Hash::make('12345678')]);
    }
}

使用命令执行seeder

php artisan db:seed --class=UserSeeder 

Laravel HttpBasicAuth 基本认证-创建中间件

php artisan make:middleware HttpBasicAuth
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class HttpBasicAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // 默认是email登录,如果想使用name则可以指定字段
        return Auth::onceBasic('name') ?: $next($request);
    }
}

Laravel HttpBasicAuth 基本认证-注册中间件

/**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array<string, class-string|string>
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        // fujuhao.com
        'auth.basic.once' => \App\Http\Middleware\HttpBasicAuth::class,
    ];

Laravel HttpBasicAuth 基本认证-创建控制器

如果输入的帐号和密码正确则会进入到Login控制器,此时可以使用Auth::user()获取当前授权用户的信息,然后生成Token返回即可。

php artisan make:controller LoginController --api
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        
        $user = Auth::user();
        return $user->createToken($user->name)->plainTextToken;
    }
}

    

Laravel HttpBasicAuth 基本认证-注册路由


use App\Http\Controllers\LoginController;
Route::apiResource('login', LoginController::class)->middleware('auth.basic.once');

请求测试

Loading...