Search code examples
symfonysymfony4lexikjwtauthbundle

Symfony - Setup the TokenController with LexikJWTAuthenticationBundle


I'm using LexikJWTAuthenticationBundle https://github.com/lexik/LexikJWTAuthenticationBundle/blob/master/Resources/doc/index.md#installation

I'm setting up my controller to get a Token:

class TokenController extends AbstractController
{
    /**
     * @Route("/api/token", name="token", methods={"POST"})
     * @param Request $request
     * @param JWTEncoderInterface $JWTEncoder
     * @return JsonResponse
     * @throws \Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTEncodeFailureException
     */
    public function token(Request $request, JWTEncoderInterface $JWTEncoder)
    {
        $user = $this->getDoctrine()->getRepository(User::class)->findOneBy([
            'email' => $request->getUser(),
        ]);

        if (!$user) {
            throw $this->createNotFoundException('User Not Found');
        }

        $isValid = $this->get('security.password_encoder')
            ->isPasswordValid($user, $request->getPassword());
        if (!$isValid) {
            throw new BadCredentialsException();
        }
        $token = $JWTEncoder->encode([
                'email' => $user->getEmail(),
                'exp' => time() + 3600 // 1 hour expiration
            ]);

        return new JsonResponse(['token' => $token]);
    }
}

But I have this error:

Service "security.password_encoder" not found: even though it exists in the app's container, the container inside "App\Controller\TokenController" is a smaller service locator that only knows about the "doctrine", "form.factory", "http_kernel", "parameter_bag", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "serializer", "session" and "twig" services. Unless you need extra laziness, try using dependency injection instead. Otherwise, you need to declare it using "TokenController::getSubscribedServices()".

I have use Dependency injection and here is my service conf

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
        public: false       # Allows optimizing the container by removing unused services; this also means
                            # fetching services directly from the container via $container->get() won't work.
                            # The best practice is to be explicit about your dependencies anyway.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

Where is the problem?


Solution

  • You are extending from AbstractController, using this controller, services that you access using $this->get() will be limited. To access the password encoder service you can inject Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface into your controller action or through the controller class constructor.

    private $passwordEncoder;
    
    public function __construct(UserPasswordEncoderInterface $passwordEncoder)
    {
      $this->passwordEncoder = $passwordEncoder;
    }
    ...
    
    $this->passwordEncoder->isPasswordValid()
    ...
    

    Or you can extend from Symfony\Bundle\FrameworkBundle\Controller\Controller for full container access. $this->get('security.password_encoder') should work with this.