Skip to content

Instantly share code, notes, and snippets.

@ValeriiVasyliev
Created May 13, 2022 08:45
Show Gist options
  • Save ValeriiVasyliev/cb7ecaab1aa1c6f2d3365c8015398180 to your computer and use it in GitHub Desktop.
Save ValeriiVasyliev/cb7ecaab1aa1c6f2d3365c8015398180 to your computer and use it in GitHub Desktop.
JSON Web Token Using PHP
// Create token header as a JSON string
$header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);

// Create token payload as a JSON string
$payload = json_encode(['user_id' => 123]);

// Encode Header to Base64Url String
$base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));

// Encode Payload to Base64Url String
$base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));

// Create Signature Hash
$signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, 'abC123!', true);

// Encode Signature to Base64Url String
$base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));

// Create JWT
$jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;

echo $jwt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment