Lexikjwtauthenticationbundle: An error occurred while trying to encode the JWT token

Created on 2 Jun 2019  路  9Comments  路  Source: lexik/LexikJWTAuthenticationBundle

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)

Most helpful comment

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

All 9 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)

i have this issue , did you find any solution ?

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

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

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

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

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!!

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

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

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AlexDupreWeb picture AlexDupreWeb  路  4Comments

astronati picture astronati  路  5Comments

mflasquin picture mflasquin  路  5Comments

Zempheroth picture Zempheroth  路  4Comments

Walkoss picture Walkoss  路  4Comments