hedera-web/web/jwt.php

81 lines
2.1 KiB
PHP
Raw Normal View History

2016-09-19 06:40:18 +00:00
<?php
namespace Vn\Web;
2016-10-17 06:52:14 +00:00
use Exception;
2016-09-19 06:40:18 +00:00
/**
* Basic class to encode, decode and verify JWT tokens. It implements the HS256
* algorithm from the RFC 7519 standard.
**/
2018-05-23 10:14:20 +00:00
class Jwt {
2016-09-19 06:40:18 +00:00
/**
* Creates a new JWT token with the passed $payload and $key.
*
* @param {Array} $payload The data to encode
* @param {string} $key The key used to sign the token
* @return {string} The new JWT token
**/
2018-05-23 10:14:20 +00:00
static function encode($payload, $key) {
2016-09-19 06:40:18 +00:00
$header = [
'alg' => 'HS256',
'typ' => 'JWT'
];
2018-05-23 10:14:20 +00:00
$b64Header = self::jsonB64Encode($header);
$b64Payload = self::jsonB64Encode($payload);
$b64Signature = self::getSignature($b64Header, $b64Payload, $key);
2016-09-19 06:40:18 +00:00
return "$b64Header.$b64Payload.$b64Signature";
}
/**
* Validates and extracts the data from a JWT token.
*
* @param {Array} $token The JWT token
* @param {string} $key The key used to validate the token
* @return {string} The JWT validated and decoded data
**/
2018-05-23 10:14:20 +00:00
static function decode($token, $key) {
$parts = explode('.', $token);
2016-09-19 06:40:18 +00:00
if (count($parts) !== 3)
2018-05-23 10:14:20 +00:00
throw new Exception('Bad JWT token');
2016-09-19 06:40:18 +00:00
$b64Header = $parts[0];
$b64Payload = $parts[1];
$b64Signature = $parts[2];
2018-05-23 10:14:20 +00:00
$header = self::jsonB64Decode($b64Header);
$payload = self::jsonB64Decode($b64Payload);
2016-09-19 06:40:18 +00:00
2018-05-23 10:14:20 +00:00
if ($b64Signature != self::getSignature($b64Header, $b64Payload, $key))
throw new Exception('Bad token signature');
2016-09-19 06:40:18 +00:00
return $payload;
}
2018-05-23 10:14:20 +00:00
static function getSignature($b64Header, $b64Payload, $key) {
$signature = hash_hmac('sha256', "$b64Header.$b64Payload", $key, TRUE);
return self::base64UrlEncode($signature);
2016-09-19 06:40:18 +00:00
}
2018-05-23 10:14:20 +00:00
static function jsonB64Encode($data) {
return self::base64UrlEncode(json_encode($data));
2016-09-19 06:40:18 +00:00
}
2018-05-23 10:14:20 +00:00
static function jsonB64Decode($data) {
return json_decode(self::base64UrlDecode($data), TRUE);
2016-09-19 06:40:18 +00:00
}
2018-05-23 10:14:20 +00:00
static function base64UrlEncode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
2016-09-19 06:40:18 +00:00
}
2018-05-23 10:14:20 +00:00
static function base64UrlDecode($data) {
$remainder = strlen($data) % 4;
$data = strtr($data, '-_', '+/');
return base64_decode(str_pad($data, $remainder, '=', STR_PAD_RIGHT));
2016-09-19 06:40:18 +00:00
}
}