PHP:
authentication_code 部分をデコードするために、実装を参照できるコード スニペットを次に示します。
function jsonWebTokenBase64Decode($string)
{
$string = str_replace('-', '+', $string);
$string = str_replace('_', '/', $string);
switch (strlen($string) % 4)
{
case 0: break;
case 2: $string .= '=='; break;
case 3: $string .= '='; break;
default: throw createInvalidAuthenticationTokenException();
}
return base64_decode($string);
}
function jsonWebTokenBase64Encode($string)
{
$string = base64_encode($string);
$string = trim($string, '=');
$string = str_replace('+', '-', $string);
return str_replace('/', '_', $string);
}
function decodeAuthenticationToken($authenticationToken, $clientSecret)
{
// Break the token into segments delimited by dots and verify there are three segments
$segments = explode('.', $authenticationToken);
if (count($segments) != 3)
{
throw createInvalidAuthenticationTokenException();
}
// Decode the segments to extract two JSON objects and the signature
$envelope = json_decode(jsonWebTokenBase64Decode($segments[0]), true);
$claims = json_decode(jsonWebTokenBase64Decode($segments[1]), true);
$signature = $segments[2];
// If the authentication token is expired, return false
if ($claims['exp'] < time())
{
return false;
}
// Verify that the algorithm and token type are correct
if ($envelope['alg'] != 'HS256')
{
throw createInvalidAuthenticationTokenException();
}
if ($envelope['typ'] != 'JWT')
{
throw createInvalidAuthenticationTokenException();
}
// Compute the signing key by hashing the client secret
$encodedClientSecret = utf8_encode($clientSecret . 'JWTSig');
$signingKey = hash('sha256', $encodedClientSecret, true);
// Concatenate the first two segments of the token and perform an HMAC hash with the signing key
$input = utf8_encode($segments[0] . '.' . $segments[1]);
$hashValue = hash_hmac('sha256', $input, $signingKey, true);
// Validate the token by base64 encoding the hash value and comparing it to the signature
$encodedHashValue = jsonWebTokenBase64Encode($hashValue);
if ($encodedHashValue != $signature)
{
throw createInvalidAuthenticationTokenException();
}
// If the token passes validation, return the user ID stored in the token
return $claims['uid'];
}