Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JWT "Signature verification failed" with PHP

Tags:

I am using Firebase/JWT with php. I am trying to read the token in "decoded" php file but it shows be Signature verification failed not sure why that is happening. This is how I am encoding the token

<?php 
use \Firebase\JWT\JWT;
require 'vendor/autoload.php';

require('config/Database.php');
$db = new Database;

$key = "helloworld";


//$jwt = JWT::encode($token, $key, 'HS512');

$post = file_get_contents("php://input");
$postdata = json_decode($post);

if($postdata){

    $email = $postdata->email;
    $password = $postdata->password;

    $query = "SELECT * FROM users WHERE email = :email";
    $db->query($query);
    $db->bind(":email", $email);
    $rows = $db->resultset();

    if(password_verify($password, $rows[0]["hash"])){
        $rows[0]["Success"] = "Success";
        $token = array(
            "rows" => $rows
        );
        $jwt = JWT::encode($token, $key, 'HS256');
        header("auth: " . $jwt);
        echo json_encode($jwt, 128);
    }else{
        echo "Failed";
    }
}


?>

Then I am decoding the token in this file

<?php 

use \Firebase\JWT\JWT;
require 'vendor/autoload.php';

require('config/Database.php');
$db = new Database;

$key = "helloworld";


//$jwt = JWT::encode($token, $key, 'HS512');

$post = file_get_contents("php://input");
$postdata = json_decode($post);


if($postdata){
    $userData = $postdata->userdata;
    // check if token is same stored in the database then decode
    $jwt = JWT::decode($userData, $key, array('HS256'));

    echo $jwt;
}
?>

It fails, returning a "Signature verification failed" error. Any help is appreciated. Thank you.

like image 209
Abubakar Saad Avatar asked Aug 09 '16 20:08

Abubakar Saad


1 Answers

The problem why it wasn't verifying was because I was using json_encode on the jwt and that caused it to be wrapped around quotes again so the token looked something like this ""eY0lkajflajk...."" and that caused the verifying exception. Thank you @zerkms for bring that up.

like image 166
Abubakar Saad Avatar answered Oct 11 '22 16:10

Abubakar Saad