Larave框架通過sanctum進行API鑒權詳解

目標

1.使用laravel框架進行用戶的登錄,註冊,認證

2.前後端分離的情況下,用戶請求接口,使用API token進行認證

步驟

安裝啟動

composer create-project laravel/laravel example-app
cd example-app   
php artisan serve

此時,通過訪問http://127.0.0.1:8000就可以看到訪問成功瞭

安裝擴展包

接下來安裝laravel官方的擴展包Sanctum,以達到目標

composer require laravel/sanctum

接下來,你需要使用 vendor:publish Artisan 命令發佈 Sanctum 的配置和遷移文件。Sanctum 的配置文件將會保存在 config 文件夾中:

php artisan vendor:publish –provider="Laravel\Sanctum\SanctumServiceProvider"

修改配置文件

然後需要修改.env文件文件裡面的數據庫配置,改為:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=caixin
DB_USERNAME=root
DB_PASSWORD=root

數據庫遷移

最後,您應該運行數據庫遷移。 Sanctum 將創建一個數據庫表來存儲 API 令牌:

php artisan migrate

接下來,如果您想利用 Sanctum 對 SPA 進行身份驗證,您應該將 Sanctum 的中間件添加到您應用的 app/Http/Kernel.php 文件中的 api 中間件組中:

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

此時查看app/Models/User.php文件,User 模型應使用 Laravel\Sanctum\HasApiTokens trait:

use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

模擬數據

此時,在數據庫中的user表中隨便加入一條數據

INSERT INTO `users` (`id`, `name`, `email`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`)
VALUES
	(1, 'java0904', '[email protected]', NULL, '', NULL, NULL, NULL);

添加訪問路由

此時在routes/api.php中配置路由,來獲取token

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
Route::post('/tokens/create', function (Request $request) {
    $user = \App\Models\User::find(1);
    模擬登陸,此時,會將用戶的session存儲,但是實際通過API認證的時候,此處用不到
//    \Illuminate\Support\Facades\Auth::login($user);
    $token =$user->createToken($user->name);
    return ['token' => $token->plainTextToken];
})->withoutMiddleware('auth:sanctum');

測試獲取token

此時訪問http://127.0.0.1:8000/api/tokens/create,就可以拿到瞭token

curl方式

curl -d '' http://127.0.0.1:8000/api/tokens/create
{"token":"7|ZbSuwu7UBDeQjvXx6iNUCcZJKsbSSO6nctmqLjDq"}

postman測試

測試其他接口

不帶token

此時,來訪問其他API接口,都需要帶上Authorization token才能訪問瞭,否則,會出現如下異常

帶上token

此時,把token帶上,效果如下

curl測試

curl -H 'Authorization: Bearer 7|ZbSuwu7UBDeQjvXx6iNUCcZJKsbSSO6nctmqLjDq' http://local.app.com/api/user
{"id":1,"name":"java0904","email":"[email protected]","email_verified_at":null,"created_at":null,"updated_at":null}

postman測試

知識點補充1

app/Providers/RouteServiceProvider.php 這個文件的作用以及核心代碼分析

<?php
class RouteServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->configureRateLimiting();
        $this->routes(function () {
            //routes/api.php這個路由文件裡面的路由,默認都會使用api中間件,並且路由前綴是/api
            Route::prefix('api')
//                ->middleware(['api'])//這裡是默認的中間件,默認隻有一個
                //這裡我加上瞭auth:sanctum這個中間件,作為全局使用,就不用為每個路由加上這個中間件瞭,但是獲取token的路由,需要排除這個中間件
                ->middleware(['api','auth:sanctum'])
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));
            //'routes/web.php'這個文件裡面的路由,默認都會使用web這個中間件
            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));
        });
    }
}

上面的代碼提到瞭兩個自帶的中間件apiweb,他們的定義在app/Http/Kernel.php文件中,它的核心代碼如下:

protected $middlewareGroups = [
        //web中間件
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            //這裡需要格外註意,所有/route/web.php中的路由,如果是post請求,都會有csrfToken的驗證,當然也可以手動給排除一些路由
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
        //api中間件
        'api' => [
             \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

註意看web中間件中有 \App\Http\Middleware\VerifyCsrfToken::class,

這行,他的作用是所有/route/web.php中的路由,如果是post請求,都會有csrfToken的驗證,當然也可以手動給排除一些路由

知識點補充2

/route/api.php

<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});
Route::post('/tokens/create', function (Request $request) {
    $user = \App\Models\User::find(1);
    模擬登陸,此時,會將用戶的session存儲,但是實際通過API認證的時候,此處用不到
    //    \Illuminate\Support\Facades\Auth::login($user);
    $token = $user->createToken($user->name);
    return ['token' => $token->plainTextToken];
})->withoutMiddleware('auth:sanctum');
Route::post('/tokens/create2', function (Request $request) {
    //這裡可以寫自己的一些驗證邏輯
    //用戶來獲取token,必須攜帶用戶名和密碼
    $password = $request->get("password");
    $username = $request->get("username");
    $user = \App\Models\User::where('password', $password)->where('username', $username)->first();
    if (!$user) {
        return [
            'code' => 500,
            'msg' => '用戶名密碼錯誤'
        ];
    }
    $token = $user->createToken($user->name);
    return ['token' => $token->plainTextToken];
})->withoutMiddleware('auth:sanctum');
//用來寫使用session,不是前後端分離的用戶登陸
Route::post('/login', function (Request $request) {
    //laravel內部的驗證方式
    if (\Illuminate\Support\Facades\Auth::attempt([
        'username' => $request->get("name"),
        'password' => $request->get("password")])) {
        //登陸成功
        //保存session
    } else {
        //登陸失敗
    }
})->withoutMiddleware('auth:sanctum');

代碼倉庫

https://github.com/silk-java/laravel-sanctum-learn

到此這篇關於Larave框架通過sanctum進行API鑒權詳解的文章就介紹到這瞭,更多相關Larave sanctum內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: