gpt4 book ai didi

laravel - 为什么与 jwt-auth 的 session 时间是登录后 1 小时?

转载 作者:行者123 更新时间:2023-12-01 23:59:45 26 4
gpt4 key购买 nike

在 laravel 7 后端 rest api 应用程序中,我使用 jwt-auth 并且在登录时遇到问题我可以在前端部分工作,但在 1 小时内我收到了 TOKEN_EXPIRED 错误。

1) 我试图将 session 时间设置得更大,但失败了。在开发阶段,我需要多 1 小时的 session 时间。继续直播,我将 session 时间设置为 30 分钟。

2) 我预计 session 更大是从登录用户的最后一次请求到后端的 1 小时,而不是从登录开始

我在下面实现了刷新方法,但看起来刷新不起作用...

应用程序/Http/Controllers/API/AuthController.php :

<?php

namespace App\Http\Controllers\API;

use App\library\CheckValueType;
use App\Settings;
use Auth;
use Config;
use DB;
use Validator;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Str;
use App\UserGroup;
use App\Http\Resources\UserCollection;
use Avatar;
use Storage;

class AuthController extends Controller
{

/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('jwt.auth', ['except' => ['login', 'register', 'activate']]);
}

public function login(Request $request)
{
$credentials = $request->only('email', 'password');

if ($token = $this->guard('api')->attempt($credentials)) {
$loggedUser = $this->guard('api')->user();

if ($loggedUser->status != 'A') {
return response()->json(['error' => 'Unauthorized'], HTTP_RESPONSE_NOT_UNAUTHORIZED);
}
$loggedUser->last_logged = Carbon::now(config('app.timezone'));
$loggedUser->save();

$userGroupsCount = UserGroup
::getByUserId($loggedUser->id)
->count();
if ($userGroupsCount == 0) {
return response()->json(['error' => 'Unauthorized'], HTTP_RESPONSE_NOT_UNAUTHORIZED);
}

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

return response()->json(['error' => 'Unauthorized'], HTTP_RESPONSE_NOT_UNAUTHORIZED);
}


public function me()
{
return response()->json($this->guard('api')->user());
}

public function logout()
{
$this->guard('api')->logout();
return response()->json(['message' => 'Successfully logged out']);
}

public function refresh()
{
return $this->respondWithToken($this->guard()->refresh());
}

protected function respondWithToken($token)
{
$loggedUser = $this->guard()->user();

$user_avatar_path = 'public/' . User::getUserAvatarPath($loggedUser->id, $loggedUser->avatar);
$filenameData = User::setUserAvatarProps($loggedUser->id, $loggedUser->avatar, true);
$usersGroups = User::getUserGroupByUserId($loggedUser->id, false);

return response()->json([
'access_token' => $token,
'user' => $loggedUser,
'token_type' => 'bearer',
'user_avatar_path' => $user_avatar_path,
'filenameData' => $filenameData,
'usersGroups' => $usersGroups,
'expires_in' => $this->guard('api')->factory()->getTTL() * 999360 // I SET VERY BIG VALUE
]);
}

public function guard()
{
return \Auth::Guard('api');
}

在/config/auth.php 中:

<?php

return [


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

'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],

'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],

'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
],

'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 99360, // I SET BIG VALUE
'throttle' => 98860,
],
],


'password_timeout' => 10800, // I SET BIG VALUE

在 app/Exceptions/Handler.php 我有:

public function render($request, Throwable $exception)
{

if ($exception instanceof UnauthorizedHttpException) {
if ($exception->getPrevious() instanceof TokenExpiredException) {
\Log::info( '-2 UnauthorizedHttpException TokenExpiredException::' ); // I SEE THIS ERROR LOGGED
return response()->json(['error' => 'TOKEN_EXPIRED'], $exception->getStatusCode());

我有:

"laravel/framework": "^7.0",
"tymon/jwt-auth": "^1.0.0",

我的配置有什么问题?

修改:

我添加了文件app/Http/Middleware/JwtMiddleware.php 内容和 1 行错误记录:

<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;

class JwtMiddleware extends BaseMiddleware
{
public function handle($request, Closure $next)
{
try {
if (! $user = $this->auth->parseToken()->authenticate()) {
return response()->json(['success' => false, 'error' => __('Invalid User.')]);
}
} catch (TokenExpiredException $e) {
try {
$refreshed = $this->auth->refresh($this->auth->getToken());
$user = $this->auth->setToken($refreshed)->toUser();
header('Authorization: Bearer ' . $refreshed);
} catch (JWTException $e) {
return response()->json(['success' => false, 'error' => __('Could not generate refresh token')]);
}
} catch (JWTException $e) {
\Log::info( '-1 JwtMiddleware$e->getMessage() ::' . print_r( $e->getMessage(), true ) );

return response()->json(['success' => false, 'error' => __('Invalid request')]);
}

return $next($request);
}
}

我在文件 app/Http/Kernel.php 中添加:

   ...
protected $middleware = [
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\App\Http\Middleware\JwtMiddleware::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class
];
...

and running the page site is broken and I see lines in log :
[2020-05-27 17:08:33] local.INFO: -1 JwtMiddleware$e->getMessage() ::The token could not be parsed from the request
[2020-05-27 17:08:33] local.INFO: -1 JwtMiddleware$e->getMessage() ::The token could not be parsed from the request
[2020-05-27 17:08:33] local.INFO: -1 JwtMiddleware$e->getMessage() ::The token could not be parsed from the request

会不会和 app/Http/Controllers/API/AuthController.php 的代码有冲突?如何修复?

修改 #2:谢谢 !我修复了错误并在 .env 中添加了以下行:

JWT_TTL=20 # 20 minutes
JWT_REFRESH_TTL=20160 # 2 weeks

并清除缓存我再次登录,结果是在我使用应用程序时没有注销任何 20 分钟,但是当我在没有使用它的情况下打开应用程序时正如我预期的那样,在大约 30 分钟的时间里,我可以在不登录的情况下继续工作。这些是其他选择吗?

修改 #3:在我的 vuejs 文件的客户端部分,我最喜欢 src/App.vue 中的请求拦截器:

created() {
let self = this
this.$http.interceptors.response.use(undefined, function (error) {

return new Promise(function (/*resolve, reject*/) {
if (typeof error.response.status !== 'undefined' && error.response.status === 401) {
self.$store.dispatch('logout') // DEBUGGING
self.showPopupMessage('Access', 'Not authorized !', 'warn')
let splitted0 = self.getSplitted(error.response.config.url, '/login', 0)

if (splitted0 == '') { // not move from login page
self.$router.push('/login') // DEBUGGING
}
}

if (typeof error.response.status !== 'undefined') {
if (error.response.status === 401) {
self.$store.dispatch('logout') // DEBUGGING
self.showPopupMessage('Access', 'Not authorized !', 'warn')
self.$router.push('/login') // DEBUGGING
}
}

throw error
})
})


}, // created() {

我在其中捕获了 401 错误,想知道是否可以捕获来自服务器的请求

header('Authorization: Bearer ' . $refreshed);

并从 $refreshed 写入新的 access_token 值?但是我怎么才能捕获它呢?但是一些特殊的返回请求代码?

谢谢!

最佳答案

转到 ---> config/jwt.php你可以这样做

'ttl' => env('JWT_TTL', 1440)

或在 Controller 中

$token = JWTAuth::attempt($credentials, ['exp' => Carbon\Carbon::now()->addDays(7)->timestamp]);

config()->set('jwt.ttl', 60*60*7);

Config::set('jwt.ttl', 60*60*7);

关于laravel - 为什么与 jwt-auth 的 session 时间是登录后 1 小时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62036938/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com