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().