我正在 Laravel 中製作 API,我想建立一個刷新令牌例程。
我使用了網站上的範例
<?php namespace AppHttpControllers; use IlluminateSupportFacadesAuth; use AppHttpControllersController; 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 IlluminateHttpJsonResponse */ public function login() { $credentials = request(['email', 'password']); if (! $token = auth()->attempt($credentials)) { return response()->json(['error' => 'Unauthorized'], 401); } return $this->respondWithToken($token); } /** * Get the authenticated User. * * @return IlluminateHttpJsonResponse */ public function me() { return response()->json(auth()->user()); } /** * Log the user out (Invalidate the token). * * @return IlluminateHttpJsonResponse */ public function logout() { auth()->logout(); return response()->json(['message' => 'Successfully logged out']); } /** * Refresh a token. * * @return IlluminateHttpJsonResponse */ public function refresh() { return $this->respondWithToken(auth()->refresh()); } /** * Get the token array structure. * * @param string $token * * @return IlluminateHttpJsonResponse */ protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => auth()->factory()->getTTL() * 60 ]); } }
但它顯示了這些錯誤 “未定義方法‘工廠’.intelephense(1013)” “未定義方法‘刷新’.intelephense(1013)”
如何執行此刷新令牌例程?以及為什麼會出現這個錯誤,在舊版本中,當JWT函式庫還是tymondesigns/jwt-auth時,不會有這個錯誤。
Laravel 9 PHP 8.1
P粉8385635232023-12-24 10:43:32
您可以使用以下命令刷新令牌
$token = JWTAuth::getToken(); $new_token = JWTAuth::refresh($token);
但是,如果您希望令牌在每個請求時刷新(不鼓勵),請在您的 app\Http\Kernel.php 中新增 jwt.refresh 中介軟體
protected $routeMiddleware = [ ... 'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken', 'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken', ];