Error : Unable to create a signed JWT from the given configuration on Symfony 6.4

44 Views Asked by At

I am currently working on Symfony 6.4 and a React front, and I'm trying to create a Login form.

When I enter the right data in the form, the controller is suppose to generate a JWT Token but I get this message : Unable to create a signed JWT from the given configuration.

Here is my .env file :

###> lexik/jwt-authentication-bundle ###
JWT_SECRET_KEY=%kernel.project_dir%/config/jwt/private.pem
JWT_PUBLIC_KEY=%kernel.project_dir%/config/jwt/public.pem
JWT_PASSPHRASE=/*passphrase*/
###< lexik/jwt-authentication-bundle ###

Here is how it is configured on the lexik_jwt_authentication.yaml file :

lexik_jwt_authentication:
    secret_key: '%env(JWT_SECRET_KEY)%' # required for token creation
    public_key: '%env(JWT_PUBLIC_KEY)%' # required for token verification
    pass_phrase: '%env(JWT_PASSPHRASE)%' # required for token creation
    token_ttl: 3600 # in seconds, default is 3600
    user_identity_field: email

My service.yaml file :

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.

    App\Controller\LoginController:
        arguments:
            $jwtManager: '@lexik_jwt_authentication.jwt_manager'

My LoginController.php :

<?php

namespace App\Controller;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
// use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTManager;
use Symfony\Component\HttpFoundation\Cookie;

class LoginController extends AbstractController
{
    private $entityManager;
    private $jwtManager;

    public function __construct(EntityManagerInterface $entityManager, JWTTokenManagerInterface $jwtManager)
    {
        $this->entityManager = $entityManager;
        $this->jwtManager = $jwtManager;
    }

    /**
     * @Route("/api/login", name="api_login", methods={"POST"})
     */
    public function login(Request $request, EntityManagerInterface $entityManager): JsonResponse
    {

        $data = json_decode($request->getContent(), true);
        $email = $data['email'] ?? "";
        $password = $data['password'] ?? "";

        $em = $entityManager;

        // Recherchez l'utilisateur dans la table des utilisateurs clients
        $user = $em->getRepository(User::class)->findOneByEmail($email);

        if ($user) {
            if (password_verify($password, $user->getPassword())) {
                //Si le mot de passe est bon, générer le token JWT
                $token = $this->jwtManager->create($user);
                // Stockage du token dans les cookie côté client
                $cookie = Cookie::create('jwt_token', $token)
                    ->withExpires(new \DateTime('+1 day'))
                    ->withPath('/')
                    ->withHttpOnly(true);

                // L'utilisateur est authentifié avec succès
                $response = new JsonResponse([
                    'message' => 'Connexion réussie',
                    'token' => $token,
                ], Response::HTTP_OK);

                $response->headers->setCookie($cookie);
                return $response;
            } else {
                // L'authentification a échoué car pas de mot de passe
                return new JsonResponse(['message' => 'Mot de passe incorrect'], Response::HTTP_UNAUTHORIZED);
            }
        } else {
            // L'authentification a échoué car email incorrect
            return new JsonResponse(['message' => 'Email incorrect'], Response::HTTP_UNAUTHORIZED);
        }
    }

}

Do you know how do I have to do it to not have this problem anymore?

0

There are 0 best solutions below