Laravel 6.0 JWT教學

JungR
JungR
Nov 2 · 9 min read
  • 首先可以參考此篇建立Laravel 6 專案
  • 安裝JWT
    請先確認進入到專案之根目錄底下。注意! tymondesigns/jwt-auth套件本為1.0.0-rc.5,該版本為更新支援至laravel 6。
composer require tymon/jwt-auth "1.0.0-rc.5"

都準備好之後,就可以進入JWT建置的章節了!


此篇教學參照該套件 tymondesigns/jwt-auth 之官方文件網站,來建置並使用Postman來戳API。

  • 新增服務提供者(Service Provider)
    新增 service providerconfig/app.php 檔案中之 providers 陣列當中。
'providers' => [
  • 發行此服務提供設定 (Publish the config)
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

這時候應該會新增一個 config/jwt.php 的檔案,裡面放置jwt的基本設定。

  • 產生私鑰(Generate secret key)
php artisan jwt:secret

做完後會更新 .env 檔案,並新增或修改 JWT_SECRET=secret_code_here


上面的基本設定都完成以後,接下來就是快速的開始:

  • 更新使用者模型(User model)

這邊的話,我們將在 app/Users.php 來實作 Tymon\JWTAuth\Contracts\JWTSubject 並實作該介面之 getJWTIdentifier()getJWTCustomClaims()

<?php
  • 設定認證(Configure Auth guard)

config/auth.php 檔案當中,將認證的部分改為jwt的認證方式。

'defaults' => [
- 'guard' => 'web',
+ 'guard' => 'api',
'passwords' => 'users',
],
  • 新增基本的認證Routes (Add some basic authentication routes)

首先,在 routes/api.php 檔案中加入以下:

Route::group([
  • 建立 AuthController
php artisan make:controller AuthController

並在 app/Http/Controllers/AuthController 檔案中加入以下:

<?php

那我們就能夠使用 Postman 來戳API囉!
用在資料表 users 中所建立的會員資料來使用。

使用Postman來 POST http://localhost/api/auth/login 並在 Headers 中加入 Content-Type: application/json

body 中使用 raw 加入:

{
"email": "your_users_table's_email",
"password": "your_users_table's_decoded_password"
}

接下來按下 Send 按鈕就會得到以下Token內容:

到這邊為止,已經成功用JWT產生Token囉!


官方文件中有幾個功能可以來使用你產生的 access_token ,例如 POST http://localhost/api/auth/me 。我們先使用POST http://localhost/api/auth/login 產生的 access_token 用在Postman工具中。

在Postman工具中之 authorization 設定 Header TypeBearer 並在Token中放入產生的 access_token

就會回傳Token內的資訊囉!

官方文件中除了 loginme 以外,還有 refreshlogout 來做使用,用下就依照你們的需求來使用。

希望此篇文章對剛接觸的人有幫助。

JungR

Written by

JungR

Attitude determines everythings!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade