主頁 > 知識庫 > Laravel配合jwt使用的方法實例

Laravel配合jwt使用的方法實例

熱門標簽:招標自動語音外呼系統(tǒng) gps 地圖標注軟件 地圖標注視頻廣告入駐 400電話鄭州申請 黔江400電話如何辦理 電銷機器人便宜的有嗎 ai電話機器人加盟代理 中原區(qū)電話機器人價格 OMG地圖標注app

測試使用的是Laravel5.5版本。

安裝

composer require tymon/jwt-auth=1.0.0-rc.5

配置

生成配置

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

php artisan jwt:secret

auth配置

?php

return [
 ...

 'defaults' => [
  'guard' => 'web',
  'passwords' => 'users',
 ],


 'guards' => [
  'web' => [
   'driver' => 'session',
   'provider' => 'users',
  ],
  // 使用jwt
  'api' => [
   'driver' => 'jwt',
   'provider' => 'apiUser',
  ],
 ],


 'providers' => [
  ...
  // 指定model
  'apiUser' => [
   'driver' => 'eloquent',
   'model' => App\ApiUser::class,
  ], 
 ],
];

編碼

控制器:

?php

namespace App\Http\Controllers\Api;

use App\ApiUser;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends Controller
{
 /**
  * 中間件去除login和refresh
  *
  * @return void
  */
 public function __construct()
 {
  $this->middleware('auth:api', ['except' => ['login','refresh']]);
 }

 /**
  * Get a JWT via given credentials.
  *
  * @return \Illuminate\Http\JsonResponse
  */
 public function login(Request $request)
 {
  $credentials = $request->only('phone', 'password');

  if (count($credentials)  2) {
   return response()->json(['error' => 'Unauthorized'], 401);
  } 

  $user = ApiUser::where('phone', $credentials['phone'])
   ->where('password', md5($credentials['password']))
   ->first();
  if (empty($user) || !$token = JWTAuth::fromUser($user)) {
   return response()->json(['error' => 'Unauthorized'], 401);
  }
  // dd($token);

  return $this->respondWithToken($token);
 }

 /**
  * Get the authenticated User.
  *
  * @return \Illuminate\Http\JsonResponse
  */
 public function me()
 {
  return response()->json(auth('api')->user());
 }

 /**
  * Log the user out (Invalidate the token).
  *
  * @return \Illuminate\Http\JsonResponse
  */
 public function logout()
 {
  auth()->logout();

  return response()->json(['message' => 'Successfully logged out']);
 }

 /**
  * Refresh a token.
  *
  * @return \Illuminate\Http\JsonResponse
  */
 public function refresh()
 {
  return $this->respondWithToken(auth('api')->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('api')->factory()->getTTL() * 60
  ]);
 }
}

路由:

此處注意,我為了方便測試,使用了get方法,生產(chǎn)環(huán)境不建議使用get。

// routes/api.php

Route::middleware('api')->prefix('auth')->namespace('Api')->group(function () {
 Route::get('login', 'AuthController@login');
 Route::post('logout', 'AuthController@logout');
 Route::get('refresh', 'AuthController@refresh');
 Route::get('me', 'AuthController@me');
});

測試一下:

unauthenticated處理

這里需要注意下,unauthenticated處理一下比較好,否則會默認跳轉(zhuǎn)login登錄頁面。

?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Auth\AuthenticationException;

class Handler extends ExceptionHandler
{
  ...

  protected function unauthenticated($request, AuthenticationException $exception)
  {
    return response()->json(['message' => 'Unauthenticated.'], 401);
     /*非api可以這么處理
    return $request->expectsJson()
          ? response()->json(['message' => 'Unauthenticated.'], 401)
          : redirect()->guest(route('login'));
          */
  }
}

加入token refresh

加入中間件代碼:

?php
namespace App\Http\Middleware;
 
use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Auth\AuthenticationException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Illuminate\Http\Exceptions\HttpResponseException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class RefreshToken extends BaseMiddleware
{

  /**
   * Handle an incoming request.
   *
   * @param \Illuminate\Http\Request $request
   * @param \Closure $next
   * @return mixed
   */
  public function handle($request, Closure $next)
  { 
    try{
      //檢查請求中是否帶有token 如果沒有token值則拋出異常
      $this->checkForToken($request); 
      if ($request->user = JWTAuth::parseToken()->authenticate()) {    
        return $next($request);
      }
      throw new AuthenticationException('Unauthorized', []);
    }catch (TokenExpiredException $exception){
      //返回特殊的code
      throw new HttpResponseException(response()->json([
        'message' => 'token expired'
      ]));
    } catch (\Exception $exception) {
      throw new AuthenticationException('Unauthorized', []);
    }
  }
}

注冊:

?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
  ...
  protected $routeMiddleware = [
    'token.refresh' => \App\Http\Middleware\RefreshToken::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
  ];
}

相應(yīng)的控制器構(gòu)造函數(shù)修改:

public function __construct()
{
    $this->middleware('token.refresh', ['except' => ['login','refresh']]);
}

把token時間設(shè)置成1分鐘,測試一下。

可以根據(jù)api返回,去調(diào)用刷新接口。

簡單使用就是這樣啦。

總結(jié)

到此這篇關(guān)于Laravel配合jwt使用的文章就介紹到這了,更多相關(guān)Laravel配合jwt使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • Laravel (Lumen) 解決JWT-Auth刷新token的問題
  • laravel5.5安裝jwt-auth 生成token令牌的示例
  • Laravel jwt 多表(多用戶端)驗證隔離的實現(xiàn)

標簽:孝感 那曲 濟源 哈密 阿里 北京 日照 池州

巨人網(wǎng)絡(luò)通訊聲明:本文標題《Laravel配合jwt使用的方法實例》,本文關(guān)鍵詞  Laravel,配合,jwt,使,用的,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Laravel配合jwt使用的方法實例》相關(guān)的同類信息!
  • 本頁收集關(guān)于Laravel配合jwt使用的方法實例的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章