使用LexikJWTAuthenticationBundle,FOSRest,FOSUser如何通過令牌獲得通過身份驗證的用戶配置文件。可能嗎?LexikJWT通過令牌獲取用戶配置文件
假設用戶已通過LexikJWT進行身份驗證,並且我有一個像/api/profile
這樣的API端點,我發送該令牌並期望獲得指定的用戶數據。
我用前端ReactJS與Redux。
使用LexikJWTAuthenticationBundle,FOSRest,FOSUser如何通過令牌獲得通過身份驗證的用戶配置文件。可能嗎?LexikJWT通過令牌獲取用戶配置文件
假設用戶已通過LexikJWT進行身份驗證,並且我有一個像/api/profile
這樣的API端點,我發送該令牌並期望獲得指定的用戶數據。
我用前端ReactJS與Redux。
這是當用戶已經認證瞭如何通過服務來獲取用戶的例子:
class UserService
{
/** @var TokenStorageInterface */
private $tokenStorage;
/**
* @param TokenStorageInterface $storage
*/
public function __construct(
TokenStorageInterface $storage,
)
{
$this->tokenStorage = $storage;
}
public function getCurrentUser()
{
$token = $this->tokenStorage->getToken();
if ($token instanceof TokenInterface) {
/** @var User $user */
$user = $token->getUser();
return $user;
} else {
return null;
}
}
}
而在你services.yml
:
tenant_user_service:
class: YourBundle\YourPackage\UserService
arguments: [ '@security.token_storage' ]
這將返回用戶 - 但請注意,根據用戶在認證過程中如何設置令牌的方式,只能將您的用戶名視爲字符串。但基本上,您可以從當前的$ token-> getUser()獲取任何內容。
我是新的,但我可以試試...
您可以像使用
@Security("is_granted('ROLE_USER')")
註釋在您的控制器和類似$this->getUser()->getUsername();
來獲取用戶名。
例如:
$user = $this->get('doctrine.orm.default_entity_manager')
->getRepository('AppBundle:User')
->FindOne($this->getUser()->getUsername());`
之後你序列DATAS,創建新的響應並返回它。
不確定是否理解您的問題 - 當您的令牌是TokenInterface的實例時,$ token-> getUser()提供了什麼? – LBA