2

I'm experimenting with jwt's and I made a really simple one in php and went to the jwt.io debugger to validate it, and the header and payload were decoded correctly, but it said that the signature was unverified. I looked at this SO question and copied this article's code exactly and wasn't able to validate with any secret key. I tried changing the string I set my secret key, selecting and deselecting the box and I couldn't get anything to validate. Here is my code:

$key = "mySecret";
$header = ["typ"=>"JWT","alg"=>"HS256"];
$header = base64_encode(json_encode($header));     
$payload = ["valid"=>"true","isAdmin"=>"false"];
$payload = base64_encode(json_encode($payload));
$signature = hash_hmac('sha256','$header.$payload', $key, true);
$signature = base64_encode($signature);
$token = "$header.$payload.$signature";
echo $token;

What step did I miss?

EDIT TO INCLUDE JWT


eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ2YWxpZCI6InRydWUiLCJpc0FkbWluIjoiZmFsc2UifQ==.QzjPt33UOjEPdPLtyhvs4DYrAD2TnQgv8P0WuHXuj/c=

Adam McGurk
  • 186
  • 1
  • 19
  • 54

1 Answers1

1

The code you linked is incorrect. The header and payload are base64 encoded but it should be base64 urlencoded. See RFC7519

A JWT is represented as a sequence of URL-safe parts separated by period ('.') characters. Each part contains a base64url-encoded value.

Try adding this function provided as comment in base64_encode documentation. Note that the SO question is also using it

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

$header = base64url_encode(json_encode($header));  
$payload = base64url_encode(json_encode($payload));  
$signature = base64url_encode($signature);
Community
  • 1
  • 1
pedrofb
  • 37,271
  • 5
  • 94
  • 142
  • Thank you! It was two issues then...that was definitely a big one, and also, when hashing the `$header.$payload` into the signature, I used single quotes instead of double, so I changed them to double, combined with the base64url_encode, and it worked! – Adam McGurk Sep 05 '17 at 13:41