LexikJWT 通过令牌获取用户个人资料 [英] LexikJWT get user profile by token

查看:64
本文介绍了LexikJWT 通过令牌获取用户个人资料的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 LexikJWTAuthenticationBundle、FOSRest、FOSUser 如何通过令牌获取经过身份验证的用户配置文件.可能吗?

Using LexikJWTAuthenticationBundle, FOSRest, FOSUser how do I get authenticated user profile by token. Is it possible?

假设用户已经通过 LexikJWT 进行了身份验证,并且我有一个像 /api/profile 这样的 api 端点,我在其中发送令牌并希望获得指定的用户数据.

So let's say user is already authenticated via LexikJWT and I have an api endpoint like /api/profile where I send the token and I expect to get specified user data.

我将 ReactJS 与 Redux 一起用于前端.

I'm using for frontend ReactJS with Redux.

推荐答案

这是一个在用户已经通过身份验证时如何通过服务获取用户的示例:

This is an example of how to get your user by a service when the user is already authenticated:

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() 中获取任何内容.

This will return your user - but be aware depending on the how user got set to the token during authentication this can be as well only your username as a string. But basically you get any content from your current $token->getUser().

这篇关于LexikJWT 通过令牌获取用户个人资料的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆