Ilmiont Ilmiont - 2 months ago 11x
PHP Question

JWT signature not verifying in PHP

I'm just getting started with token-based authentication and have written a very simple PHP script to create a JWT. However, when I run it in's debugger, the signature never verifies.

$secret = "super_secure_private_key";

function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), "+/", "-_"), "=");

$header = base64url_encode(json_encode([
"alg" => "HS256",
"typ" => "JWT"

$payload = base64url_encode(json_encode([
"name" => "James Walker",
"privileges" => "total"

$signature = base64url_encode(hash_hmac("sha256", $header . "." . $payload, $secret));

$token = $header . "." . $payload . "." . $signature;

As far as I can tell, my implementation is inline with the formatting of JWT. Have I missed something, or should I use a library e.g. php-jwt to generate new tokens and get them verified?

For my use, my implementation would probably work alright anyway, since I can still verify the tokens myself using the same code. But I'm just not sure why isn't verifying the signature.


This issue gave me a big headache when I first wrote my JWT implementation. The trick is that the keyed hash that creates the signature must output raw binary data, but the default setting of hash_hmac is not that.

Change how you generate your signature from:

hash_hmac("sha256", $header . "." . $payload, $secret);


hash_hmac("sha256", $header . "." . $payload, $secret, true);

See info about the last parameter in the manual