從零開始系列-Laravel編寫api服務介面:5.中介軟體驗證JWT登陸

lixueyuan發表於2021-05-12

前言: 再第 3 章中介紹瞭如何使用多使用者的jwt認證,下面講講怎麼實現 jwt 多使用者鑑權

  1. 路由檔案

路由介面檔案應該充分分組,按照系統的業務邏輯分成:

所有模組->不需要登入(比如通用的分類、圖片上傳等)

使用者模組->不需要登入 (登入、註冊、找回密碼等)

使用者模組->需要登入

管理員模組->不需要登入(比如登入、註冊、找回密碼等)

管理員模組->需要登入

閒話少敘,下面是路由程式碼 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::get('/user', function (Request $request) {
    return ['asdf'];
});


// 配置dingo路由
$api = app('Dingo\Api\Routing\Router');

// 預設Accept application/prs.hospital.v1+json
$api->version('v1', ['namespace' => 'App\Http\Controllers\V1', 'middleware' => []], function ($api) {

    // 公共路由
    $api->group(['as' => 'common', 'prefix' => 'common', 'namespace' => 'Common', 'middleware' => []], function ($api) {
        // 登入獲取token
        $api->post('authorization', 'AuthorizationController@store')
            ->name('.authorizations.store');
        // 重新整理token
        $api->get('refresh_token', 'AuthorizationsController@refresh')
            ->name('.authorizations.refresh');
        // 退出登入
        $api->get('log_out', 'AuthorizationsController@logOut')
            ->name('.authorizations.refresh');
    });

    //管理員後臺介面
    $api->group(['as' => 'admin', 'prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => []], function ($api) {
        //需要登入後的介面
        $api->group(['middleware' => ['auth:admin']], function ($api) {
            $api->get('me','AdminsController@me');
        });
    });

    // 使用者員介面
    $api->group(['as' => 'user', 'prefix' => 'user', 'namespace' => 'User', 'middleware' => []], function ($api) {
        //需要登入後的介面
        $api->group(['middleware' => ['auth:user']], function ($api) {
            $api->get('me','UsersController@me');
        });
    });
});

補上對應的控制器

php artisan make:controller V1/Admin/AdminsController

php artisan make:controller V1/User/UsersController

UsersController程式碼都一樣這裡只寫AdminsController

<?php

namespace App\Http\Controllers\V1\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AdminsController extends Controller
{
    public function me()
    {
        return auth('admin')->user();
    }
}

訪問介面:get http://homestead.test/api/admin/me
header裡面加上剛才生成的token
Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9ob21lc3RlYWQudGVzdFwvYXBpXC9jb21tb25cL2F1dGhvcml6YXRpb24iLCJpYXQiOjE2MTAzNTM5MjUsImV4cCI6MTYxODEyOTkyNSwibmJmIjoxNjEwMzUzOTI1LCJqdGkiOiJLNW1ZenZsOEY3N1A0azl0Iiwic3ViIjoxLCJwcnYiOiJkZjg4M2RiOTdiZDA1ZWY4ZmY4NTA4MmQ2ODZjNDVlODMyZTU5M2E5In0.NYZKW2wbfMPAjLF-d-oA88OMrCNo8WHy7wAM_zhxlzU
訪問結果:

{
    "id": 1,
    "name": "Helmer Graham",
    "account": "38129",
    "password": "$2y$10$rQ54Rh.FMPGWR8q9Oq8UUOCH4YYLurx2MPK/4aDgnh0yLh6Ow7sTa",
    "created_at": "2021-01-08T09:33:56.000000Z",
    "updated_at": "2021-01-08T09:33:56.000000Z"
}

別忘了要刪除這一段(最新版本的laravel會預設走這裡,舊版沒這個跳轉)
app\Http\Middleware\Authenticate.php

    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
//        if (! $request->expectsJson()) {
//            return route('login');
//        }
    }

使用者控制器也是一樣控制器guard改一下就行了

return auth('user')->user();
// 下面寫法同樣有效
dump($request->user());
dump(auth('admin')->user());
dump(\Illuminate\Support\Facades\Auth::user());
dump(\Illuminate\Support\Facades\Auth::guard('admin')->user());

至此完成!是不是很簡單。

本作品採用《CC 協議》,轉載必須註明作者和本文連結
程式設計兩年半,喜歡ctrl(唱、跳、rap、籃球)

相關文章