除了前台用 API 做前後端分離,並使用 JWT 作為認證之外,這次要來將後台也用API 做前後端分離,同樣也使用 JWT 作為認證。
請參考 JWT 套件官網 說明
安裝 JWT
composer require tymon/jwt-auth
產生 JWT config 檔案
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
產生 JWT 金鑰
php artisan jwt:secret
修改 .env 檔案
JWT_SECRET=
# 設定JWT被清除時間(分鐘), 預設 refresh_ttl 是兩周, 太長需修改, 即使登出該令牌將持續兩周有效. 建議將它縮短並在登出功能強制讓該令牌失效.
JWT_REFRESH_TTL=60
JWT_TTL=60
修改 config\auth.php
'guards' => [
....
//前台 User API
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
....
//後台 Admin API
'admapi' => [
'driver' => 'jwt',
'provider' => 'admins',
'hash' => false,
],
],
修改 app\Http\Kernel.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
//新增一個API用的Middleware給admin用
'admapi' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
修改 User 及 Admin 模型 加入 JWT implement
//JWT用
use Tymon\JWTAuth\Contracts\JWTSubject;
//加入 JWTSubject implements 及 官方提供的兩個 function
class User extends Authenticatable implements JWTSubject
{
use 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 [];
}
}
修改 route\api.php 建立 API 用 Route
//前台 user api 用的路由 網址看起來就像 https://localhost/api/{名稱}
use App\Http\Controllers\API\UserLoginController;
Route::post('login', [UserLoginController::class , 'login']);
Route::post('logout', [UserLoginController::class , 'logout']);
Route::post('refresh', [UserLoginController::class , 'refresh']);
Route::post('me', [UserLoginController::class , 'me']);
Route::post('list', [UserLoginController::class , 'list']);
//後台 admin api 用的路由 網址看起來就像 https://localhost/api/admin/{名稱}
use App\Http\Controllers\API\Admin\AdminLoginController;
Route::prefix('admin')->group(function() {
Route::post('login', [AdminLoginController::class , 'login']);
Route::post('logout', [AdminLoginController::class , 'logout']);
Route::post('refresh', [AdminLoginController::class , 'refresh']);
Route::post('me', [AdminLoginController::class , 'me']);
Route::post('list', [AdminLoginController::class , 'list']);
});
建立 前台 API 用 UserLoginController
php artisan make:controller API\UserLoginController
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Validator;
use App\Models\User as UserDB;
use Illuminate\Support\Facades\Auth;
class UserLoginController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
//除了 login 其餘 function 都要經過 api 的 middleware 檢查
$this->middleware('api', ['except' => ['login']]);
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
//驗證
$validator = Validator::make($credentials, [
'email' => 'required|email',
'password' => 'required|min:4',
]);
//驗證失敗返回訊息
if ($validator->fails()) {
return response()->json(['error' => '帳號密碼錯誤'], 400);
}
//透過Auth取得JWT token
if (! $token = auth('api')->attempt($credentials)) {
return response()->json(['error' => '授權失敗'], 401);
}
//將token拋出
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth('api')->user());
}
/**
* Get the Admins list.
*
* @return \Illuminate\Http\JsonResponse
*/
public function list()
{
$users = UserDB::paginate(5);
return response()->json($users);
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
//找出登入者資料
// $user = auth('api')->user();
//JWT RAW data
// $payload = auth('api')->payload();
//重新更新token
// $newtoken = auth('api')->refresh();
// return $this->respondWithToken($newtoken);
//抓取是否有返回token
// $token = request(['token']);
//如果沒使用者存在則給出錯誤訊息
if(!auth('admapi')->user()){
return response()->json(['error' => 'Unauthorized'], 401);
}
//將該token列入失效名單並登出
auth('api')->invalidate();
auth('api')->logout();
return response()->json(['message' => 'Successfully logged out'], 200);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
$newToken = auth('api')->refresh();
return $this->respondWithToken($newToken);
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'user' => auth('api')->user(), //將使用者資料一起帶出
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL(),
]);
}
}
建立 後台 API 用 AdminLoginController
php artisan make:controller API\Admin\AdminLoginController
<?php
namespace App\Http\Controllers\API\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Validator;
use App\Models\Admin as AdminDB;
class AdminLoginController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
//除了 login 其餘 function 都要經過 api 的 middleware 檢查
$this->middleware('admapi', ['except' => ['login']]);
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
//驗證
$validator = Validator::make($credentials, [
'email' => 'required|email',
'password' => 'required|min:4',
]);
//驗證失敗返回訊息
if ($validator->fails()) {
return response()->json(['error' => '帳號密碼錯誤'], 400);
}
//透過Auth取得JWT token
if (! $token = auth('admapi')->attempt($credentials)) {
return response()->json(['error' => '授權失敗'], 401);
}
//將token拋出
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth('admapi')->user());
}
/**
* Get the Admins list.
*
* @return \Illuminate\Http\JsonResponse
*/
public function list()
{
$admins = AdminDB::paginate(5);
return response()->json($admins);
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
//找出登入者資料
// $usser = auth('admapi')->user();
//JWT RAW data
// $payload = auth('api')->payload();
//重新更新token
// $newtoken = auth('api')->refresh();
// return $this->respondWithToken($newtoken);
//抓取是否有返回token
// $token = request(['token']);
//如果沒使用者存在則給出錯誤訊息
if(!auth('admapi')->user()){
return response()->json(['error' => 'Unauthorized'], 401);
}
//將該token列入失效名單並登出
auth('admapi')->invalidate();
auth('admapi')->logout();
return response()->json(['message' => 'Successfully logged out'], 200);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
$newToken = auth('admapi')->refresh();
return $this->respondWithToken($newToken);
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'user' => auth('admapi')->user(), //將使用者資料一起帶出
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth('admapi')->factory()->getTTL(),
]);
}
}
測試