laravel 安裝jwt-auth及驗證
1、使用composer安裝jwt, cmd到專案資料夾中;
composer require tymon/jwt-auth 1.0.*(這裡版本號碼依自己的需求寫)
安裝jwt ,參考官方文件https: //jwt-auth.readthedocs.io/en/docs/laravel-installation/
2、如果laravel版本低於5.4
開啟根目錄下的config/app. php
在'providers'陣列裡加上Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
'providers' => [ ... Tymon\JWTAuth\Providers\LaravelServiceProvider:: class,]
3、在config 下增加一個jwt.php 的設定檔
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
4、在.env 檔案下產生一個加密金鑰,如:JWT_SECRET=foobar
php artisan jwt:secret
5、在user模型中寫入下列程式碼
<?php namespace App\Model; use Tymon\JWTAuth\Contracts\JWTSubject; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable implements JWTSubject { // Rest omitted for brevity protected $table="user"; public $timestamps = false; public function getJWTIdentifier() { return $this->getKey(); } public function getJWTCustomClaims() { return []; } }
6、註冊兩個Facade
config/app.php
'aliases' => [ ... // 添加以下两行 'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth', 'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory', ],
7、修改auth.php
config/auth.php
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'jwt', // 原来是 token 改成jwt 'provider' => 'users', ], ],
8、註冊路由
Route::group([ 'prefix' => 'auth' ], function ($router) { $router->post('login', 'AuthController@login'); $router->post('logout', 'AuthController@logout'); });
9、建立token控制器
php artisan make:controller AuthController
##程式碼如下:<?php namespace App\Http\Controllers; use App\Model\User; use Illuminate\Http\Request; use Tymon\JWTAuth\Facades\JWTAuth; class AuthController extends Controller { /** * Create a new AuthController instance. * * @return void */ public function __construct() { $this->middleware('auth:api', ['except' => ['login']]); } /** * Get a JWT via given credentials. * * @return \Illuminate\Http\JsonResponse */ public function login() { $credentials = request(['email', 'password']); if (! $token = auth('api')->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()->json(JWTAuth::parseToken()->touser()); } /** * Log the user out (Invalidate the token). * * @return \Illuminate\Http\JsonResponse */ public function logout() { JWTAuth::parseToken()->invalidate(); return response()->json(['message' => 'Successfully logged out']); } /** * Refresh a token. * * @return \Illuminate\Http\JsonResponse */ public function refresh() { return $this->respondWithToken(JWTAuth::parseToken()->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' => JWTAuth::factory()->getTTL() * 60 ]); } }
<?php namespace App\Http\Middleware; use Auth; use Closure; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Http\Middleware\BaseMiddleware; use Tymon\JWTAuth\Exceptions\TokenExpiredException; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; // 注意,我们要继承的是 jwt 的 BaseMiddleware class RefreshToken extends BaseMiddleware { /** * Handle an incoming request. * * @ param \Illuminate\Http\Request $request * @ param \Closure $next * * @ throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException * * @ return mixed */ public function handle($request, Closure $next) { // 检查此次请求中是否带有 token,如果没有则抛出异常。 $this->checkForToken($request); // 使用 try 包裹,以捕捉 token 过期所抛出的 TokenExpiredException 异常 try { // 检测用户的登录状态,如果正常则通过 if ($this->auth->parseToken()->authenticate()) { return $next($request); } throw new UnauthorizedHttpException('jwt-auth', '未登录'); } catch (TokenExpiredException $exception) { // 此处捕获到了 token 过期所抛出的 TokenExpiredException 异常,我们在这里需要做的是刷新该用户的 token 并将它添加到响应头中 try { // 刷新用户的 token $token = $this->auth->refresh(); // 使用一次性登录以保证此次请求的成功 Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']); } catch (JWTException $exception) { // 如果捕获到此异常,即代表 refresh 也过期了,用户无法刷新令牌,需要重新登录。 throw new UnauthorizedHttpException('jwt-auth', $exception->getMessage()); } } // 在响应头中返回新的 token return $this->setAuthenticationHeader($next($request), $token); } }
$request->headers->set('Authorization','Bearer '.$token);
'RefreshToken' => \App\Http\Middleware\RefreshToken::class,
Route::group(['prefix' => 'user'],function($router) { $router->get('userInfo','UserController@userInfo')->middleware('RefreshToken'); });
laravel教學!
以上是laravel安裝jwt-auth及驗證(實例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!