在 Laravel 9 中使用'PHP-Open-Source-Saver/jwt-auth”库刷新令牌
P粉637866931
P粉637866931 2023-12-23 15:50:34
0
1
619

我正在 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粉637866931
P粉637866931

全部回复(1)
P粉838563523

您可以使用以下命令刷新令牌

$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',
];
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板