教材

Untitled

示範教材

Untitled

作業教材

實作示範

Step 1.下載 JWT-Auth 套件

composer require tymon/jwt-auth:dev-develop

Step 2.發布套件設定檔

接著發布套件的設定檔,也就是名為 jwt.php 的設定檔,位於 config 資料夾

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

Step 3.生成 JWT 憑證

接著要在 .env 檔案去產生 JWT 憑證,若憑證為空,則被視為非法身分

php artisan jwt:secret

Step 4.修改 User 模型

重點在宣告 User 模型實作 JWTSubject 介面,並加入下列2個方法:

//app\\Models\\User.php

namespace App\\Models;

use Tymon\\JWTAuth\\Contracts\\JWTSubject;
use Illuminate\\Notifications\\Notifiable;
use Illuminate\\Foundation\\Auth\\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    ... (略)

    /**
     * 取得 JWT 辨識字串
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * 回傳鍵值對陣列,內容包含被加入 JWT 的自定義 Payload
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

Step 5.修改驗證設定