composer create-project --prefer-dist laravel/laravel sample "5.5.*"
composer install
composer require tymon/jwt-auth or 在composer.json中添加 `"tymon/jwt-auth": "^1.0.0-rc.2",` 終端:composer update
在config/app.php
的providers
中php
'providers' => [ ... Tymon\JWTAuth\Providers\LaravelServiceProvider::class, ]
終端運行:php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
會產生config/jwt.php
的配置文件laravel
再運行:php artisan jwt:secret
生成keyweb
運行:json
php artisan make:model Models/Admin -m php artisan make:model Models/User -m
database/migrations下
遷移文件中api
**admins:** Schema::create('admins', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->string('avatar')->nullable(); $table->timestamps(); }); **users:** Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->string('avatar')->nullable(); $table->timestamps(); });
<?php namespace App; use Tymon\JWTAuth\Contracts\JWTSubject; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; 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 []; } }
在config/auth.php
中配置,找到對應的修改爲本身的跨域
'guards' => [session
'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'jwt', 'provider' => 'users', ], 'admin' => [ 'driver' => 'jwt', 'provider' => 'admins', ],
],app
'providers' => [cors
'users' => [ 'driver' => 'eloquent', 'model' => App\Models\User::class, 'table' => 'users', ], 'admins' => [ 'driver' => 'eloquent', 'model' => App\Models\Admin::class, 'table' => 'admin_users' ],
],composer
在routes/api.php
Route::group([
'middleware' => 'api', 'prefix' => 'auth'
], function ($router) {
Route::post('login', 'AuthController@login'); Route::post('logout', 'AuthController@logout'); Route::post('refresh', 'AuthController@refresh'); Route::post('me', 'AuthController@me');
});
運行:php artisan make:controller AdminController
建立控制器
注:此處主要是用了guard('admin')
來區分要調用的表和Model這裏是在auth.php
中配置的
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; class AdminController extends Controller { /** * Create a new AuthController instance. * * @return void */ public function __construct() { $this->middleware('myauth', ['except' => ['login']]); } /** * Get a JWT via given credentials. * * @return \Illuminate\Http\JsonResponse */ public function login() { $credentials = request(['email', 'password']); if (! $token = auth()->guard('admin')->attempt($credentials)) { return response()->json(['error' => 'Unauthorized'], 401); } return $this->respondWithToken($token); } /** * Get the authenticated User. * * @return \Illuminate\Http\JsonResponse */ public function me() { return response()->guard('admin')->json(auth()->user()); } /** * Log the user out (Invalidate the token). * * @return \Illuminate\Http\JsonResponse */ public function logout() { auth()->guard('admin')->logout(); return response()->json(['message' => 'Successfully logged out']); } /** * Refresh a token. * * @return \Illuminate\Http\JsonResponse */ public function refresh() { return $this->respondWithToken(auth()->guard('admin')->refresh()); } /** * Get the token array structure. * * @param string $token * * @return \Illuminate\Http\JsonResponse */ protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => auth()->factory()->getTTL() * 60 ]); } }
因爲使用了多表認證,因此不能使用jwt自帶的中間鍵auth:api or jwt.auth
,我本身建了一箇中間鍵[myauth
]來作路由驗證。
在app/Http/Middleware下新建
namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class AuthMiddleware { public function handle($request, Closure $next) { try { $user = auth()->guard('admin')->userOrFail(); if(!$user) { return response()->json(['message' => 'jwt 無效'], 401); } } catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) { return response()->json(['message' => 'jwt 無效'], 401); } return $next($request); } }
而後在app/Http/Kernel
的$routeMiddleware
下添加
protected $routeMiddleware = [
... 'cors' => \App\Http\Middleware\ClientRequestCors::class, //自定義的跨域中間鍵 'myauth' => \App\Http\Middleware\AuthMiddleware::class, ... ];
在路由和Controller下的構造函數調用。
因爲時間關係,沒有在PostMan截圖了,參考此文章的小夥伴自行進行測試
下面例子源用了不少jwt-auth文檔代碼