设置流明jwt令牌中的到期时间

时间:2016-04-16 14:36:42

标签: laravel jwt lumen

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

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

现在我该如何解决?

5 个答案:

答案 0 :(得分:4)

如果你跑了:

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

 ...

答案 1 :(得分:1)

实际上,对我来说,它仅在我更改exp上的JWT::encode参数时起作用。

在我的代码上,使用登录后,我发送了一些响应。遵循我的所有代码。 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'));
}

我希望它能为您提供帮助。

答案 2 :(得分:0)

JWT_TTL中,最新的(变体> 1.0.0)流明.env将在内部代码中使用'ttl' => env('JWT_TTL', 60),时起作用。
参考:https://github.com/tymondesigns/jwt-auth/blob/develop/config/config.php

答案 3 :(得分:0)

我正在使用Lumen (5.8.12),实际上是像这样enter image description here.env文件中设置值

只需将JWT_TTL的值添加到.env文件中即可。默认时间为60分钟,此处的值代表1440(60 * 24)分钟或1天

答案 4 :(得分:0)

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

JWT_TTL=1440

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

相关问题