從零開始系列-Laravel編寫api服務介面:3.JWT多使用者訪問

lixueyuan發表於2021-05-12

jwt (json web token)

簡介

jwt 就不說了,是一種普遍的後端 api 授權方式,這個寫完之後再寫一個go版本和java版本的 :) 閒話少敘,怎麼實現一個多使用者認證呢,下面開始。

github.com/tymondesigns/jwt-auth

文件 jwt-auth.readthedocs.io/

需求:

有一個使用者表,一個管理員表,要求使用者和管理員都可以登陸並且檢視或者稽核文章,做一個登陸介面獲取token並且驗證token

下面開始:

  1. 開始安裝

composer require tymon/jwt-auth

  1. 釋出配置檔案

    php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

    用命令生成jwtkey

# 這條命令會在 .env 檔案下生成一個加密金鑰,如:JWT_SECRET=xadsfasdf
php artisan jwt:secret
  1. 進行一些配置

由於要用到多使用者配置所以要配置多個模型

php artisan make:model User

php artisan make:model Admin

User.php 程式碼如下:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject // 必須實現JWTSubject介面
{
    use HasFactory, Notifiable;


    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [
        'id'
    ];
}

Admin.php 程式碼如下:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;

class Admin extends Model implements JWTSubject
{
    use HasFactory;


    /**
     * @inheritDoc
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * @inheritDoc
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

開啟config/auth.php檔案改為如下:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'user' => [
            'driver' => 'jwt',
            'provider' => 'users',
            'hash' => false,
        ],
        'admin' => [
            'driver' => 'jwt',
            'provider' => 'admins',
            'hash' => false,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
         'admins' => [// key 對應上面的guards裡面對應的 provider 
             'driver' => 'eloquent',
             'model' => App\Models\Admin::class, // 這個模型繼承了jwtSubject介面
         ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];
  1. 編寫登陸介面

多說一句多端登陸介面一般都是通用的,可以放在各模組下,也可以用公共模組,此處用統一登陸介面
新建登陸控制器(此處用的是restfull api的控制器結構,你可以去掉–resource)

php artisan make:controller V1\common\AuthorizationController --resource

AuthorizationController.php 方法下放入以下程式碼:
記得在app\Http\Controllers\Controller.php裡面use helpers;就是 dingo 擴充套件檔案

<?php

namespace App\Http\Controllers;

use Dingo\Api\Routing\Helpers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    use Helpers; // 應用dingo的helpers
}
    <?php

namespace App\Http\Controllers\V1\common;

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

class AuthorizationController extends Controller
{

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $guard = $request->guard;// 區分是user還是admin type就是guard
        if (!config('auth.guards.' . $guard)) {
            return $this->response->errorUnauthorized('使用者型別不存在');
        }
        $credentials = []; // 登陸驗證欄位
        switch ($guard) {
            case 'user':
                $credentials = $request->only(['email', 'password']);
                break;
            case 'admin':
                $credentials = $request->only(['account', 'password']);
                break;
        }
        $token = auth($guard)->attempt($credentials);
        if (!$token){
            return $this->response()->errorUnauthorized('賬號或密碼錯誤');
        }
        return $this->respondWithToken($token,$guard); // type就是guard
    }


    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return $this->user();// 一般用auth($guard)->user();至於如何用this需要再中介軟體裡面處理詳情請看第`5`章
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout($guard)
    {
        auth($guard)->logout();

        return $this->response()->array(['message' => '退出登陸']);
    }

    /**
     * Refresh a token.
     * 重新整理token,如果開啟黑名單,以前的token便會失效。
     * 值得注意的是用上面的getToken再獲取一次Token並不算做重新整理,兩次獲得的Token是並行的,即兩個都可用。
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh($guard)
    {
        return $this->respondWithToken(auth($guard)->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token, $guard)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth($guard)->factory()->getTTL() * 60
        ]);
    }

}

新增登陸路由檔案:

// 公共路由
$api->group(['as' => 'common', 'prefix' => 'common', 'namespace' => 'Common', 'middleware' => []], function ($api) {
    // 登入獲取token
    $api->post('authorization', 'AuthorizationController@store')
        ->name('.authorizations.store');
});

訪問:

email:hansen.idella@example.com
guard:user
password:123456

homestead.test/api/common/authoriza...
傳入對應引數,就可以了

{
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9ob21lc3RlYWQudGVzdFwvYXBpXC9jb21tb25cL2F1dGhvcml6YXRpb24iLCJpYXQiOjE2MTAwOTg0NDUsImV4cCI6MTYxMDEwMjA0NSwibmJmIjoxNjEwMDk4NDQ1LCJqdGkiOiJzYkFFZXdJbzFLWjZrU0IyIiwic3ViIjoxLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.61tRyGj-iD3-rEzLti1GLzgCJ35of_88-4-R0PQi_5E",
    "token_type": "bearer",
    "expires_in": 3600
}

傳入:

guard:admin
password:123456
account:38129

返回

{
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9ob21lc3RlYWQudGVzdFwvYXBpXC9jb21tb25cL2F1dGhvcml6YXRpb24iLCJpYXQiOjE2MTAzNTM5MjUsImV4cCI6MTYxODEyOTkyNSwibmJmIjoxNjEwMzUzOTI1LCJqdGkiOiJLNW1ZenZsOEY3N1A0azl0Iiwic3ViIjoxLCJwcnYiOiJkZjg4M2RiOTdiZDA1ZWY4ZmY4NTA4MmQ2ODZjNDVlODMyZTU5M2E5In0.NYZKW2wbfMPAjLF-d-oA88OMrCNo8WHy7wAM_zhxlzU",
    "token_type": "bearer",
    "expires_in": 7776000
}

另外配置jwt檔案:

.env檔案下面加上

# jwt
JWT_SECRET=VN3L60yj9zjcwwX0W70Ep6grzOlFe5QE
JWT_TTL=129600 #3 * 30 * 24 * 60 #token過期時間 單位為分鐘 3個月
JWT_REFRESH_TTL=20160 #重新整理token過期時間 單位為分鐘
JWT多使用者鑑權已經全部完成,是不是很簡單?
本作品採用《CC 協議》,轉載必須註明作者和本文連結
程式設計兩年半,喜歡ctrl(唱、跳、rap、籃球)

相關文章