在 lumen jwt token 中设置过期时间

Set expire time in lumen jwt token

我使用 jwt 和 Lumen 创建了一个身份验证api。

我在我的 Lumen 项目中使用 tymondesigns/jwt-auth 包进行身份验证。在用户登录的项目中,我想在 1 个月后使用户令牌过期。

现在我该如何解决?

如果你运行:

php artisan vendor:publish

根据安装 wiki:https://github.com/tymondesigns/jwt-auth/wiki/Installation

然后简单地更改 ttl 设置:

// In config/jwt.php

...

/*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 1 hour
|
*/

'ttl' => 43800, // valid for 1 month

 ...

事实上,对我来说,当我在 JWT::encode 处更改 exp 参数时它才起作用。

在我的代码中,使用登录后我发送了一些响应。遵循我的所有代码。 exp 使用第三种方法。

/**
 * Authenticate a user and return the token if the provided credentials are correct.
 *
 * @param Request $request
 * @return mixed
 * @internal param Model $user
 */
public function authenticate(Request $request)
{
    $this->validate($this->request, [
        'email' => 'required|email',
        'password' => 'required'
    ]);
    // Find the user by email
    $user = User::where('email', $this->request->input('email'))->first();
    if (!$user) {
        return $this->responseError('USER_DOES_NOT_EXISTS', 404);
    }

    // Verify the password and generate the token
    if (Hash::check($this->request->input('password'), $user->password)) {
        return $this->responseUserData($user);
    }

    // Bad Request response
    return $this->responseError('EMAIL_OR_PASSWORD_WRONG', 403);
}

/**
* Create response json
* @param $user
* @return \Illuminate\Http\JsonResponse
*/
private function responseUserData($user)
{
    return response()->json([
        'token' => $this->jwt($user),
        'user' => $user->getUserData()
    ], 200);
}

/**
 * Create a new token.
 *
 * @param  \App\User $user
 * @return string
 */
protected function jwt(User $user)
{
    $payload = [
        'iss' => "lumen-jwt", // Issuer of the token
        'sub' => $user->id, // Subject of the token
        'iat' => time(), // Time when JWT was issued.
        'exp' => time() + 60 * 60 * 60 * 24 // Expiration time
    ];

    // As you can see we are passing `JWT_SECRET` as the second parameter that will
    // be used to decode the token in the future.
    return JWT::encode($payload, env('JWT_SECRET'));
}

希望对你有所帮助

在最新(版本 >1.0.0)上,.env 中的 lumen JWT_TTL 将工作,因为他们在其内部代码中使用 'ttl' => env('JWT_TTL', 60),
参考:https://github.com/tymondesigns/jwt-auth/blob/develop/config/config.php

我正在使用 Lumen (5.8.12) 我真正做的是在 .env 文件中像这样设置值

只需在您的.env file.The 中添加JWT_TTL 的值默认时间是60 分钟这里我的值代表1440(60*24) 分钟或1 天

我使用的是Lumen 8.0版本。我刚刚在 .env 文件中添加了以下行 24 小时,并在命令行中重新启动了项目,它就像魅力一样工作:

JWT_TTL=1440

注意:请不要忘记在命令行中重启项目。乐于帮助和分享此代码。感谢您提出这个问题。