Created
July 30, 2024 09:07
-
-
Save md-riaz/3e8e964a70ad7aa134cc993e09cfc3a5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
class JWT { | |
private $secretKey; | |
public function __construct($secretKey) { | |
$this->secretKey = $secretKey; | |
} | |
public function generateToken($payload, $expiration = 3600) { | |
$header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']); | |
$payload['exp'] = time() + $expiration; | |
$payload = json_encode($payload); | |
$base64UrlHeader = $this->base64UrlEncode($header); | |
$base64UrlPayload = $this->base64UrlEncode($payload); | |
$signature = hash_hmac('sha256', "$base64UrlHeader.$base64UrlPayload", $this->secretKey, true); | |
$base64UrlSignature = $this->base64UrlEncode($signature); | |
return "$base64UrlHeader.$base64UrlPayload.$base64UrlSignature"; | |
} | |
public function verifyToken($token) { | |
$parts = explode('.', $token); | |
if (count($parts) !== 3) { | |
return false; | |
} | |
$header = $parts[0]; | |
$payload = $parts[1]; | |
$signatureProvided = $parts[2]; | |
$base64UrlHeader = $header; | |
$base64UrlPayload = $payload; | |
$signature = hash_hmac('sha256', "$base64UrlHeader.$base64UrlPayload", $this->secretKey, true); | |
$base64UrlSignature = $this->base64UrlEncode($signature); | |
if ($base64UrlSignature !== $signatureProvided) { | |
return false; | |
} | |
$payload = json_decode($this->base64UrlDecode($base64UrlPayload), true); | |
if ($payload['exp'] < time()) { | |
return false; | |
} | |
return $payload; | |
} | |
private function base64UrlEncode($data) { | |
return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($data)); | |
} | |
private function base64UrlDecode($data) { | |
return base64_decode(str_replace(['-', '_'], ['+', '/'], $data)); | |
} | |
} | |
// Usage example | |
$secretKey = 'your-secret-key'; | |
$jwt = new JWT($secretKey); | |
$payload = [ | |
'user_id' => 123, | |
'username' => 'john_doe' | |
]; | |
// Generate token | |
$token = $jwt->generateToken($payload); | |
echo "Generated Token: " . $token . "\n"; | |
// Verify token | |
$verifiedPayload = $jwt->verifyToken($token); | |
if ($verifiedPayload) { | |
echo "Token is valid. Payload: "; | |
print_r($verifiedPayload); | |
} else { | |
echo "Token is invalid or expired."; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment