Giorgos Karyofyllis
Giorgos Karyofyllis

Reputation: 119

How to verify JWT signature in PHP?

I have a function that generates a JWT :

function getToken($user, $expTime){
   $jwt = \Firebase\JWT\JWT::encode([
     'iss' => request()->getBaseUrl(),
     'sub' => "{$user['id']}",
     'exp' => $expTime,
     'iat' => time(),
     'nbf' => time(),
     'is_admin' => $user['role_id'] == 1
 
  ], getenv("SECRET_KEY"), 'HS256');
 return $jwt;
}

This function returns the below token:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJcL2FwaSIsInN1YiI6InVzNWIzY2M4YmRlMDc4MSIsImV4cCI6NTUxMDY1ODkyNDAwMCwiaWF0IjoxNTMwNzM4NTkwLCJuYmYiOjE1MzA3Mzg1OTAsImlzX2FkbWluIjpmYWxzZX0.3bMaxCaMprURZEDurnckZWSoDRp7ePMxZXDW0B6q6fk

When I use this token to make a request I get that:

{
  "status": "error",
  "message": "Signature verification failed"
}

To make it work I go to https://jwt.io/, add the key and verify it by passing the secret.

Then I get this token :

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIvYXBpIiwic3ViIjoidXM1YjNjYzhiZGUwNzgxIiwiZXhwIjo1NTEwNjU4OTI0MDAwLCJpYXQiOjE1MzA3Mzg1OTAsIm5iZiI6MTUzMDczODU5MCwiaXNfYWRtaW4iOmZhbHNlfQ.heF_L9LrFp7Hht2dbVtOMx_gdUtmPKzrMgxW1_jdWLo

And this works fine. But how to verify it with php code so I can send it to the user?

Code for response:

function loginUser($email, $password) {

    try {
        // Connecting to databas
        $db = new db();
        $db = $db->connect();

        $user = findUserByEmail($email, $db);

        if(empty($user)){
            echo 'User not found';
            exit;
        }
        if(!password_verify($password, $user['password'])) {
            echo 'Password does not match';
            exit;
        } 

        $expTime = time() * 3600;

        $jwt = getToken($user, $expTime);

        // Close databse
        $db = null;
        
    } catch(PDOException $e){
        echo $e->getMessage();
    }

    return $jwt;
}

Upvotes: 1

Views: 11383

Answers (2)

6006604
6006604

Reputation: 7789

If you're landing on this page because of a "Signature verification failed" Google search, here is one thing to consider. I was getting this error because there were two spaces between "Bearer" and my token in the Authorization header.

Wrong:

Authorization:Bearer  eyJraWQiOiJDT2N...

Correct:

Authorization:Bearer eyJraWQiOiJDT2N...

Upvotes: 1

Giorgos Karyofyllis
Giorgos Karyofyllis

Reputation: 119

Ok finally I made it work by changing a little the function that generates the token:

function getToken($user, $expTime){
    $key = "secretkey";
    $token = array(
      'iss' => request()->getBaseUrl(),
      'sub' => "{$user['id']}",
      'exp' => $expTime,
      'iat' => time(),
      'nbf' => time(),
      'is_admin' => $user['role_id'] == 1
  );
  return JWT::encode($token, $key);
}

Upvotes: 0

Related Questions