我正在使用帶有自定義身份驗證器的 Symfony 5.4,它讀取和驗證每個請求的 JWT。
JWT 內部是我需要在控制器中訪問的資料。
我不想在控制器中重新讀取 JWT,而是存盤解碼的資料,甚至是該資料的 1 個元素,這樣就不需要在控制器中重新讀取它。
訪問在驗證器中檢測到的資料的有效方法是什么,以便在控制器操作的背景關系中可用?
uj5u.com熱心網友回復:
我會在 Symfony 中為此實作服務,應該是這樣的
<?php
namespace App\Service;
use Symfony\Component\HttpFoundation\RequestStack;
class JWTInterceptor
{
protected $request;
protected $data;
public function __construct(RequestStack $requestStack)
{
$this->request = $requestStack->getCurrentRequest();
// Get JWT token from request header, decode and store it in $this->data
}
// Get decoded data
public function getData()
{
return $this->data;
}
}
在您的控制器中,只需使用依賴注入來插入服務并呼叫JWTInterceptor::getData()以使用解碼的資料。
還應該有其他方法,例如使用EventListener or EventSubscriber或實作具有相關方法的根/基本控制器,并使其可供所有子控制器訪問等。
或者,如果您使用的是https://github.com/lexik/LexikJWTAuthenticationBundle,它已經與事件一起打包,因此您可以根據需要進行修改。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/453310.html
標籤:交响乐
