LexikJWTAuthenticationBundle icon indicating copy to clipboard operation
LexikJWTAuthenticationBundle copied to clipboard

An error occurred while trying to encode the JWT token

Open jbiddulph opened this issue 5 years ago • 11 comments

Please help, I just implemented teh LexikJWTAuthenticationBundle and I get the error:

An error occurred while trying to encode the JWT token. Please verify your configuration (private key/passphrase)

jbiddulph avatar Jun 02 '19 09:06 jbiddulph

Please help, I just implemented teh LexikJWTAuthenticationBundle and I get the error:

An error occurred while trying to encode the JWT token. Please verify your configuration (private key/passphrase)

i have this issue , did you find any solution ?

behrooz avatar Jun 29 '19 12:06 behrooz

Hi,

I have the same problem, but only when I create user by custom post method on api using usermanger service. The server throws Error 500 and traces not run.

I solve the problem that you have got using the next sentence into vhost on apache2: SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

And generate pem with 512 length: openssl genrsa -out config/jwt/private.pem -aes256 512 openssl rsa -pubout -in config/jwt/private.pem -out config/jwt/public.pem

All endpoints that need athorization or specific method (PUT, POST) run right, but POST api/user dont run properly usemanagerinterface:

UserController:

public function __construct(LoggerInterface $logger, UserManagerInterface $service) { $this->logger = $logger; $this->service = $service; } public function createUsuario(Request $request): JsonResponse { $usuarioDTO = $this->container->get('serializer')->deserialize($request->getContent(), UsuarioDTO::class, 'json'); $usuarioToCreate = new Usuario(); $usuarioToCreate->setUsername($usuarioDTO ->getUserName()) ->setPlainPassword($usuarioDTO ->getPassword()) ->setEmail($usuarioDTO ->getEmail()); $usuarioToCreate->setEnabled(true); $usuarioToCreate->getRoles() == null?$usuario->setRoles(['ROLE_USER']):null; $usuarioToCreate->getRoles() == null?$usuario->setSuperAdmin(false):null;

    $this->userManager->updateUser($usuarioToCreate);
    return new JsonResponse(
        json_decode($this->container->get('serializer')->serialize(
            new UsuarioDTO(
                $usuarioToCreate->getId(),
                $usuarioToCreate->getUserName(),
                $usuarioToCreate->getEmail())
        , 'json')),
        JsonResponse::HTTP_CREATED
    );
}

This problem only is reproduce on production environment using apache (with nginx I didnt test).

On local, with server-dev all fine.

Regards

turiaso avatar Jul 02 '19 23:07 turiaso

change the JWT_PASSPHRASE in .env with the passphrase you choose when configuring the private key

binou95diallo avatar Dec 03 '19 22:12 binou95diallo

Run from root path openssl genrsa -out config/jwt/private.pem -aes256 512 and write any your private passphrase. That passphrase copy inside .env file:

JWT_PASSPHRASE=passphrase

marinsagovac avatar Jan 18 '20 20:01 marinsagovac

This error can happens also if you have some special chars in your pass phrase. Remove them and it will works.

lionelkimbs avatar Feb 23 '20 16:02 lionelkimbs

Hi I'm having the same issue... I already regenerate the pivate.pem, and public.pem, also checked the passphrase several times, I try with postman and also with my ReactJS interface usign axios

async handleSubmit(e){
        e.preventDefault();
        console.log(this.state);

        const headers = {
            'Content-Type': 'application/json'
        }

        try{
            let response = API.post('/login_check', this.state, {headers: headers
            })
            console.log(response);
        }
        catch( e ){
            console.log('ERROR', e);
        }
    }

, but always get the same error. :( this is my .env file I generate the private.pem and public.pem with that exactly passphrase, I'm using symfony 5.0 with flex 1.3.1 for the backend, and lexik/jwt-authentication-bundle 2.6

###> 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=algo
###< lexik/jwt-authentication-bundle ###

and this is my security.yaml

providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        login:
            pattern: /api/login
            anonymous: true
            stateless: true
            json_login:
                check_path: /api/login_check
                username_path: email
                password_path: password
                require_previous_session: false                
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
        register:
            pattern:  ^/api/register
            stateless: true
            anonymous: true
        api:
            pattern: ^/api
            stateless: true
            anonymous: false
            provider: app_user_provider
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator

        main:
            anonymous: true

    access_control:
         - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/api/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/api, roles: IS_AUTHENTICATED_FULLY }

this is my lexik_jwt_authentication.yaml

lexik_jwt_authentication:
    secret_key: '%env(resolve:JWT_SECRET_KEY)%'
    public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
    pass_phrase: '%env(resolve:JWT_PASSPHRASE)%'
    token_ttl:   3600

NOTE: the symfony server logs said this |INFO | SECURI User has been authenticated successfully but after that i get this error |CRITI| REQUES Uncaught PHP Exception Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTEncodeFailureException: "An error occurred while trying to encode the JWT token. Please verify your configuration (private key/passphrase)" at ....\vendor\lexik\jwt-authentication-bundle\Encoder\LcobucciJWTEncoder.php line 37

thanks in advance!!

SOLVED: Well i figure it out... the problem was in the lexik_jwt_authentication.yml int pass_phrase I replace the: '%env(resolve:JWT_PASSPHRASE)%' for the real pass_phrase and it works!! Here the final yaml file

lexik_jwt_authentication:
    secret_key: '%env(resolve:JWT_SECRET_KEY)%'
    public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
    pass_phrase: 'algo'
    token_ttl:   3600

I hope it healp someone. Regards!!

MarlonAEC avatar Jun 10 '20 18:06 MarlonAEC

it looks like in you environment (container, vm, local machine) something goes wrong with environment, probably you've refreshed passphrase in env file, but it wasn't refreshed in machine. Faced with that problem. Didn't find out how to fix it, so just regenerated jwt certificates with old ones

IlyaSavich avatar Jun 19 '20 17:06 IlyaSavich

it looks like in you environment (container, vm, local machine) something goes wrong with environment, probably you've refreshed passphrase in env file, but it wasn't refreshed in machine. Faced with that problem. Didn't find out how to fix it, so just regenerated jwt certificates with old ones

thanks for the answer... I already fixed but... well, i didn't find where the problem was, I just regenerated the certificates like a million time ahah ... but well I'm happy it works :) ...

MarlonAEC avatar Jun 20 '20 22:06 MarlonAEC

Same problem here ! I solved it moving my "/config/jwt" to "/src/config/jwt". You have to create your "jwt" folder inside "src" folder, not in the root directory.

fgrx avatar Nov 25 '20 10:11 fgrx

For anyone encounter this issue and you are using the latest version of the bundle, you can use command php bin/console lexik:jwt:generate-keypair to generate keys.

https://github.com/lexik/LexikJWTAuthenticationBundle/blob/2.x/Resources/doc/index.md#prerequisites

change the JWT_PASSPHRASE in .env with the passphrase you choose when configuring the private key

Seems like this is the solution for this issue.

fd6130 avatar Sep 19 '21 03:09 fd6130

hi, I'm facing the same issue, none of the solution above worked for me.

SF 5.4.9 using ApiPlatform. (nginx server && PHP8.1)

I have same error : "hydra:description": "An error occurred while trying to encode the JWT token. Please verify your configuration (private key/passphrase)",

I checked my passphrase multiple times, i tested with plain passphrase in the lexik_jwt_authentication.yaml file, i tried to move folder in src, an i used the command php bin/console lexik:jwt:generate-keypair to generate keys.

Nothing seems to work i'm stuck with this error for 2 days now.

Can someone help me ?

here is my lexik_jwt_authentication.yaml code: lexik_jwt_authentication: secret_key: '%env(resolve:JWT_SECRET_KEY)%' public_key: '%env(resolve:JWT_PUBLIC_KEY)%' pass_phrase: '%env(resolve:JWT_PASSPHRASE)%' token_ttl: 3600

my .env : JWT_SECRET_KEY=%kernel.project_dir%/config/jwt/private.pem JWT_PUBLIC_KEY=%kernel.project_dir%/config/jwt/public.pem JWT_PASSPHRASE=passphrase

i tried this command on my terminal:

sudo php bin/console lexik:jwt:generate-keypair --overwrite

Thank you.

zazzou avatar Jun 04 '22 12:06 zazzou

Hi,

I have the same problem, but only when I create user by custom post method on api using usermanger service. The server throws Error 500 and traces not run.

I solve the problem that you have got using the next sentence into vhost on apache2: SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

And generate pem with 512 length: openssl genrsa -out config/jwt/private.pem -aes256 512 openssl rsa -pubout -in config/jwt/private.pem -out config/jwt/public.pem

All endpoints that need athorization or specific method (PUT, POST) run right, but POST api/user dont run properly usemanagerinterface:

UserController:

public function __construct(LoggerInterface $logger, UserManagerInterface $service) { $this->logger = $logger; $this->service = $service; } public function createUsuario(Request $request): JsonResponse { $usuarioDTO = $this->container->get('serializer')->deserialize($request->getContent(), UsuarioDTO::class, 'json'); $usuarioToCreate = new Usuario(); $usuarioToCreate->setUsername($usuarioDTO ->getUserName()) ->setPlainPassword($usuarioDTO ->getPassword()) ->setEmail($usuarioDTO ->getEmail()); $usuarioToCreate->setEnabled(true); $usuarioToCreate->getRoles() == null?$usuario->setRoles(['ROLE_USER']):null; $usuarioToCreate->getRoles() == null?$usuario->setSuperAdmin(false):null;

    $this->userManager->updateUser($usuarioToCreate);
    return new JsonResponse(
        json_decode($this->container->get('serializer')->serialize(
            new UsuarioDTO(
                $usuarioToCreate->getId(),
                $usuarioToCreate->getUserName(),
                $usuarioToCreate->getEmail())
        , 'json')),
        JsonResponse::HTTP_CREATED
    );
}

This problem only is reproduce on production environment using apache (with nginx I didnt test).

On local, with server-dev all fine.

Regards

Thanks a lot @turiaso. I had the same issue and my problem was solved by adding the following to my apache configuration ! SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

You save my day and maybe more !

adorey avatar Jul 19 '23 15:07 adorey