Last active
April 17, 2020 18:20
-
-
Save SethVandebrooke/8ee518e4c8c1eabebc6a47ad3ca72f7f to your computer and use it in GitHub Desktop.
PHP implementation of JWT
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 | |
/* | |
// EXAMPLE USE | |
// construct web token manager | |
$jwt = new JWT("SecretKey"); | |
// ^ init JWT with a server side secret key ^ | |
// sign token | |
$token = $jwt->sign([ | |
"username" => "john doe" | |
"role" => "admin" | |
]); | |
// ^ sign a token object and get a token string ^ | |
// verify token | |
$jwt->verify($token); | |
// ^ if the verification is successful, the token object will be returned ^ | |
// ^ if it isn't, it will return false ^ | |
*/ | |
class JWT { | |
// declare private secret property | |
private $secret; | |
// init | |
public function __construct($secret) { | |
// store secret | |
$this->secret = $secret; | |
} | |
// internal hash function | |
private function hash($str) { | |
return hash("sha256", $str); | |
} | |
// internal data encoding function | |
// this function base64 encodes a JSON string representation of the given data | |
// data being any object or array | |
private function encode($data) { | |
// encode as JSON, then base64 and then return the result | |
return base64_encode(json_encode($data)); | |
} | |
// internal string decoding function | |
// this function decodes a base64 into a JSON string and then parses the JSON | |
// | |
private function decode($string) { | |
return json_decode(base64_decode($string)); | |
} | |
public function sign($payload = []) { | |
// generate and encode header | |
$header = $this->encode([ | |
"alg" => "SHA256", | |
"typ" => "JWT" | |
]); | |
// generate and append initiated at property | |
$payload["iat"] = date("c"); | |
// encode payload | |
$payload = $this->encode($payload); | |
// fetch token secret | |
$secret = $this->secret; | |
// generate signature | |
$signature = $this->hash($header . "." . $payload . $secret); | |
return $header . "." . $payload . "." . $signature; | |
} | |
public function verify($token) { | |
$parts = explode(".", $token); | |
if (count($parts) <= 2) { | |
// failed validation | |
return false; | |
} | |
$header = $parts[0]; | |
$payload = $parts[1]; | |
$signature = $parts[2]; | |
$generatedSignature = $this->hash($header . "." . $payload . $this->secret); | |
if ($signature == $generatedSignature) { | |
try { | |
$header = $this->decode($header); | |
$payload = $this->decode($payload); | |
} catch (exception $err) { | |
return false; | |
} | |
return $payload; | |
} else { | |
return false; | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment