phpsymfonyjwtapi-platform.com

Symfony/ Api platorm/JWT get the current user after login


Good morning to all Please i need help. I am using JWT Authentication and all works well.But my problem is to retreive the current user after the login. I saw in the documentation that i can create a controller to do so, but after doing that i get the error of id parameter not given. Here is my controller related to the user entity

// api/src/Controller/GetMeAction.php

namespace App\Controller;

use App\Entity\User;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;

class GetMeAction
{
    /**
     * @param Security
     */
    private $_security;

    public function __construct(Security $security)
    {
        $this->_security = $security;
    }

    /**
     * @Route(
     *     name="get_me",
     *     path="get/me",
     *     methods={"GET"},
     *     defaults={
     *         "_api_resource_class"=User::class,
     *         "_api_item_operation_name"="get_me"
     *     }
     * )
     */
    public function __invoke(Request $request): User
    {
        return $this->_security->getUser();
    }
}

Solution

  • Previous answer is right, but you forgot to Extend you controller from abstract one:

    namespace App\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    
    class AdminController extends AbstractController
    {
    }
    

    If you want to get User in the service, you can Inject Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface in your __construct()

    and you can get user like:

    public function getUser(): ?User
    {
        $token = $this->tokenStorage->getToken();
    
        if (!$token) {
            return null;
        }
    
        $user = $token->getUser();
    
        if (!$user instanceof User) {
            return null;
        }
    
        return $user;
    }