Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP JWT Token Invalid Signature

Tags:

php

jwt

slim

I'm searching for an hours now and can't find a solution to this problem.

This is the code to generate JWT token. I used https://github.com/firebase/php-jwt library.

        $tokenId    = base64_encode(mcrypt_create_iv(32));
        $issuedAt   = time();
        $notBefore  = $issuedAt + 10;             //Adding 10 seconds
        $expire     = $notBefore + 60;            // Adding 60 seconds
        $serverName = 'serverName'; // Retrieve the server name from config file

        $secretKey = base64_decode(getenv('JWT_SECRET'));

         $data = [
            'iat'  => $issuedAt,         // Issued at: time when the token was generated
            'jti'  => $tokenId,          // Json Token Id: an unique identifier for the token
            'iss'  => $serverName,       // Issuer
            'nbf'  => $notBefore,        // Not before
            'exp'  => $expire,           // Expire
            'data' => [                  // Data related to the signer user
                'userId'   => '1', // userid from the users table
                'userName' => $UserName, // User name
            ]
        ];

        $jwt = JWT::encode(
                $data,      //Data to be encoded in the JWT
                $secretKey, // The signing key
                'HS256'     // Algorithm used to sign the token
        );

        $unencodedArray = ['jwt' => $jwt];
        echo json_encode($unencodedArray);

And I verify the token at https://jwt.io/

enter image description here

Can anybody help me with this problem? I'm currently new in JWT. Btw, my project is Slim API.

Thank you very much.

like image 308
Joseph Avatar asked Sep 06 '25 03:09

Joseph


1 Answers

Signature verification fails because you are not passing the correct secret key to https://jwt.io/ You need to pass the value of $secretKey from the PHP code. According to the screenshot you are passing string secret.

like image 83
Mika Tuupola Avatar answered Sep 07 '25 23:09

Mika Tuupola