LexikJWT通过令牌获取用户档案

时间:2017-02-12 20:29:51

标签: symfony profile lexikjwtauthbundle

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

因此,假设用户已经通过LexikJWT进行了身份验证,我有一个api端点,例如/api/profile,我发送令牌,我希望得到指定的用户数据。

我正在使用Redux的前端ReactJS。

2 个答案:

答案 0 :(得分:7)

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

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()获得任何内容。

答案 1 :(得分:0)

我是新手,但我可以试试......

你可以使用像

这样的注释
@Security("is_granted('ROLE_USER')")

在你的控制器和$this->getUser()->getUsername();之类的内容中获取用户名。

示例:

$user = $this->get('doctrine.orm.default_entity_manager')
    ->getRepository('AppBundle:User')
    ->FindOne($this->getUser()->getUsername());`

之后,您序列化数据,创建新的响应并返回它。