提问人:HMCodaemon 提问时间:11/17/2023 最后编辑:Tim LewisHMCodaemon 更新时间:11/17/2023 访问量:26
在 laravel Controller Contructor 中,调用函数并访问会话不起作用
In laravel Controller Contructor calling a function and accessing the session is not working
问:
我正在使用 laravel 9。 在laravel中,我创建了一个具有构造函数的控制器,因为我从该文件中包含了一个自定义类文件,我在构造函数中调用了该函数。在该函数中,我正在访问始终为 NULL 的 Session 值。
use App\Common\{JwtTokenChecker};
class AbcController extends Controller
{
public function __construct()
{
$this->jwt_token = new JwtTokenChecker();
$this->jwt_token->checkExpiryTimeToGenerateToken();
}
}
类函数:
public function checkExpiryTimeToGenerateToken()
{
$check_before_token_expire = env('CHECK_TOKEN_EXPIRE_BEFORE_TIME');
$session = app('session'); // or app('Illuminate\Session\Store') or
resolve('Illuminate\Session\Store')
$ses_token = $session->get('jwt_token');
$ses_expire = $session->get('jwt_token_expire_in');
$currentTime = now()->timestamp;
$currentTimeExpire = now()->timestamp + $ses_expire - $check_before_token_expire;
//dd($ses_token, $ses_expire, $currentTime, $currentTimeExpire);
if($currentTimeExpire <= $currentTime)
{
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer ' . session()->get('jwt_token');
$result = $this->curlObject->callCurlMethod('GET','refresh', null, $headers);
if(!empty($result))
{
$result = json_decode($result);
//dd($result);
if(isset($result->access_token))
{
$session->put('jwt_token', $result->access_token);
$session->put('jwt_token_expire_in', $result->expires_in);
}
}
}
}
错误 => 会话为 null
答:
0赞
Martin Bean
11/17/2023
#1
控制器在处理请求之前由框架实例化,因此没有会话或经过身份验证的用户可供访问。
如果你试图授权在请求中传递一个JWT,那么你应该在中间件中执行此操作;不在控制器的构造函数中。
评论
__construct()