laravel8.x--JWT

MTyu發表於2022-08-05

composer安裝jwt-auth

composer require tymon/jwt-auth

config/app.php註冊服務提供者

'providers' => [
    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]
'aliases' => [
    'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
    'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
]

釋出生成配置檔案

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

執行後config下自動生成jwt.php檔案

生成JWT_SECRET

php artisan jwt:secret

執行後會在.env中自動生成:

JWT_SECRET=IVYIoZuMhB2vUE6HQQOinyYhSL2DMhuVxsRNVAqkEzO3W3Qe9nG3G5SIH6GQG1Bd

config/auth.php中配置guards

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],
'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
    ],

更改model檔案app\Models\User.php

<?php

namespace App\Models;

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

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * 獲取會儲存到 jwt 宣告中的標識
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * 返回包含要新增到 jwt 宣告中的自定義鍵值對陣列
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return ['role' => 'user'];
    }
}

router/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::group([
    'prefix' => 'v1/auth'
], function () {
    Route::post('login', [\App\Http\Controllers\AuthController::class, 'login'])->name('login');
    Route::post('logout', [\App\Http\Controllers\AuthController::class, 'logout'])->name('logout');
    Route::post('refresh', [\App\Http\Controllers\AuthController::class, 'refresh'])->name('refresh');
    Route::get('user', [\App\Http\Controllers\AuthController::class, 'user'])->name('user');
});

建立相應控制器AuthController.php

<?php

namespace App\Http\Controllers;

use App\Models\User;

class AuthController extends Controller
{
    protected $userModel;

    public function __construct ()
    {
        $this->userModel = new User();

        $this->middleware('auth:api',['except' => ['login']]);
    }

    public function login ()
    {
        $credentials = request(['nickname', 'password']);
        if (!$token = auth('api')->attempt($credentials)) {
            return json_encode(['code' => 500, 'msg'  => '登入失敗,請檢查使用者名稱或密碼']);
        }
        return $this->respondWithToken($token);
    }

    public function respondWithToken ($token) {
        return json_encode([
            'code' => 200,
            'msg' => '成功',
            'data' => [
                'access_token' => $token,
                'token_type'   => 'bearer',
                'expires_in'   => auth('api')->factory()->getTTL() * 60
            ]
        ]);
    }

    public function user ()
    {
        return json_encode([
            'code' => 200,
            'msg'  => '成功',
            'data' => auth('api')->user()
        ]);
    }

    public function logout ()
    {
        auth('api')->logout();
        return json_encode(['code' => 200, 'msg' => '退出成功']);
    }

    public function refresh ()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }
}

測試

  • login

laravel8.x--jwt

  • user

laravel8.x--jwt

  • logout

laravel8.x--jwt

  • refresh

laravel8.x--jwt

本作品採用《CC 協議》,轉載必須註明作者和本文連結