LexikJWT get user profile by token

ⅰ亾dé卋堺 提交于 2020-12-06 07:21:04

问题


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

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.

I'm using for frontend ReactJS with Redux.


回答1:


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;
        }
    }
}

And in your services.yml:

tenant_user_service:
    class: YourBundle\YourPackage\UserService
    arguments: [ '@security.token_storage' ]

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




回答2:


i'm new but i can try...

you can use the annotation like

@Security("is_granted('ROLE_USER')")

in your controller and something like$this->getUser()->getUsername(); to get the username.

example:

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

after that you serialize datas, create new Response and return it.



来源:https://stackoverflow.com/questions/42192877/lexikjwt-get-user-profile-by-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!