Skip to content

Instantly share code, notes, and snippets.

@yakubenko
Last active April 2, 2018 06:49
Show Gist options
  • Save yakubenko/51e9bdee5307d4e77dc1878dd02f0d4d to your computer and use it in GitHub Desktop.
Save yakubenko/51e9bdee5307d4e77dc1878dd02f0d4d to your computer and use it in GitHub Desktop.
Simple JWT component for CakePHP 3
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Utility\Security;
class JTokensComponent extends Component {
public $secretKey;
public $algorythm = "HS256";
public $type = "JWT";
public $payload = [];
public $signature;
/**
* this option affects how much time will be given to the token
* strict - 1 day
* middle - 1 week
* low - 1 month
* no
* */
public $expireMode = 'strict';
private function encryptHeader() {
$data = [
'alg' => $this->algorythm,
'typ' => $this->type
];
$json = json_encode($data);
return base64_encode($json);
}
private function setExpires() {
$expires = false;
switch($this->expireMode) {
case 'strict':
$expires = strtotime("+ 1 day",time());
break;
case 'middle':
$expires = strtotime("+ 1 week",date());
break;
case 'low':
$expires = strtotime("+ 1 month",date());
break;
}
return $expires;
}
private function encryptPayLoad() {
$expires = $this->setExpires();
if($expires!==false) {
$this->payload['exp'] = $expires;
}
$json = json_encode($this->payload);
return base64_encode($json);
}
public function getTokenPayload($token) {
$parts = explode(".",$token);
return base64_decode($parts[1]);
}
public function makeToken() {
$key = (empty($this->secretKey))?Security::salt():$this->secretKey;
$header = $this->encryptHeader();
$payload = $this->encryptPayLoad();
$signature = base64_encode(hash_hmac('sha256', $header.'.'.$payload, $key, true));
return $header.'.'.$payload.'.'.$signature;
}
public function validateFormat($token) {
}
public function validateToken($token) {
$parts = explode(".",trim($token));
$signature = base64_encode(hash_hmac('sha256', $parts[0].'.'.$parts[1], $this->secretKey, true));
$payload = $parts[1];
if(!empty($payload['exp']) && $payload['exp']<=date()) {
return false;
}
// return hash_equals($parts[2],$signature);
return $parts[2]===$signature;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment