Skip to content

Instantly share code, notes, and snippets.

@kirilkirkov
Last active February 17, 2021 17:54
Show Gist options
  • Save kirilkirkov/d0c498de78364c86c81f89522027ff7c to your computer and use it in GitHub Desktop.
Save kirilkirkov/d0c498de78364c86c81f89522027ff7c to your computer and use it in GitHub Desktop.
Generate and Validate JWT Token. Its EASY!
<?php
// RFC base64 encode - https://tools.ietf.org/html/rfc7515#appendix-C
$secret = 'kiro';
// Make base64 valid for url's
function base64UrlEncode($text)
{
return str_replace(
['+', '/', '='],
['-', '_', ''],
base64_encode($text)
);
}
// Create the token header
$header = json_encode([
'typ' => 'JWT',
'alg' => 'HS256'
]);
// Create the token payload
$payload = json_encode([
'user_id' => 1,
'role' => 'admin',
'exp' => time()
]);
// Encode Header
$base64UrlHeader = base64UrlEncode($header);
// Encode Payload
$base64UrlPayload = base64UrlEncode($payload);
// Create Signature Hash
$signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, $secret, true);
// Encode Signature to Base64Url String
$base64UrlSignature = base64UrlEncode($signature);
// Create JWT
$jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
echo "Your token:\n" . $jwt . "\n";
<?php
$secret = 'kiro';
// Make base64 valid for url's
function base64UrlEncode($text)
{
return str_replace(
['+', '/', '='],
['-', '_', ''],
base64_encode($text)
);
}
$jwt = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJyb2xlIjoiYWRtaW4iLCJleHAiOjE1ODQ4MDg0MzF9.3iMPQAX9yLhlilOqi8JLxqnakUr_m9uFk1c5vEE2F1s';
$secret = 'kiro';
// split the token
$tokenParts = explode('.', $jwt);
$header = base64_decode($tokenParts[0]);
$payload = base64_decode($tokenParts[1]);
$signatureProvided = $tokenParts[2];
$tokenExpired = json_decode($payload)->exp >= time() ? false : true;
// build a signature based on the header and payload using the secret
$base64UrlHeader = base64UrlEncode($header);
$base64UrlPayload = base64UrlEncode($payload);
$signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, $secret, true);
$base64UrlSignature = base64UrlEncode($signature);
// verify it matches the signature provided in the token
$signatureValid = ($base64UrlSignature === $signatureProvided);
echo "Header:\n" . $header . "\n";
echo "Payload:\n" . $payload . "\n";
if ($tokenExpired) {
echo "Token has expired.\n";
} else {
echo "Token has not expired yet.\n";
}
if ($signatureValid) {
echo "The signature is valid.\n";
} else {
echo "The signature is NOT valid\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment