Created
June 7, 2021 16:45
-
-
Save fukasawah/c4eeb7ec6a95450b0252056292f67801 to your computer and use it in GitHub Desktop.
PHPでHS256なJWTを作る
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function encodeBase64Url($value) | |
{ | |
$value = base64_encode($value); | |
$value = strtr($value, '+/', '-_'); // https://datatracker.ietf.org/doc/html/rfc4648#section-5 | |
$value = rtrim($value, "="); // without padding, https://datatracker.ietf.org/doc/html/rfc7515#appendix-C | |
return $value; | |
} | |
function generateJwtHS256($payload, $tokenKeyB64) | |
{ | |
$tokenKeyBin = base64_decode($tokenKeyB64); | |
$header = [ | |
'typ' => 'JWT', | |
'alg' => 'HS256' | |
]; | |
$header = encodeBase64Url(json_encode($header)); | |
$payload = encodeBase64Url(json_encode($payload)); | |
$signature = hash_hmac('sha256', "{$header}.{$payload}", $tokenKeyBin, true); | |
$signature = encodeBase64Url($signature); | |
return "{$header}.{$payload}.{$signature}"; | |
} | |
$secret = base64_encode(random_bytes(16)); | |
$token = generateJwtHS256([ | |
"iss" => "foo", | |
"aud" => "bar", | |
"exp" => time() | |
], $secret); | |
echo "secret: $secret\n"; | |
echo "token: $token\n"; | |
// eg.) | |
// secret: gs/RbSR4KLeUpOubuDVmpQ== | |
// token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJmb28iLCJhdWQiOiJiYXIiLCJleHAiOjE2MjMwODM1Mzd9.0Bwx70s5xVCGYhpm47990D50FE4V4uRX3U9ZSeNQDwk | |
// check https://jwt.io/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment