Created
February 2, 2016 23:27
-
-
Save RafaelKa/5c26957569ef5422ab8e to your computer and use it in GitHub Desktop.
Garbage collection for one-time JWTs in voryx/Thruway apps. Note: No validation and sign verification included here.
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 | |
namespace Acme\Package\Security\Authentication\Provider; | |
use Lcobucci\JWT\Parser; | |
use Lcobucci\JWT\Signer; | |
use Lcobucci\JWT\Signer\BaseSigner; | |
use Lcobucci\JWT\Token; | |
use Lcobucci\JWT\ValidationData; | |
use React\EventLoop\LoopInterface; | |
use Thruway\Authentication\AbstractAuthProviderClient; | |
/** | |
* Class JWTProvider | |
*/ | |
class JWTProvider extends AbstractAuthProviderClient | |
{ | |
// ... | |
/** | |
* Is called after object initialization | |
* | |
* Move contents of this method if neccessery | |
*/ | |
public function initializeObject() | |
{ | |
$this->getLoop()->addPeriodicTimer(60, call_user_func($this, 'collectGarbage')); | |
} | |
/** | |
* Json Web Tokens cache for one time usage | |
* @var array | |
*/ | |
protected $usedJwts = [ | |
// jti => exp | |
]; | |
/** | |
* Adds jti to used JWTs | |
* | |
* @param Token $jwt | |
* @return void | |
*/ | |
protected function markJwtAsUsed(Token $jwt) | |
{ | |
$this->usedJwts[$jwt->getClaim('jti')] = $jwt->getClaim('exp'); | |
} | |
/** | |
* Checks if JWT currently in use | |
* | |
* @param Token $jwt | |
* @return bool | |
*/ | |
protected function isJwtUsed(Token $jwt) | |
{ | |
return isset($this->usedJwts[$jwt->getClaim('jti')]); | |
} | |
/** | |
* Removes expired JWTs from used JWTs | |
* | |
* expired tokens are rejected anyway | |
* | |
* @return void | |
*/ | |
public function collectGarbage() | |
{ | |
$currentTimestamp = (new \DateTime())->getTimestamp(); | |
foreach ($this->usedJwts as $jti => $exp) { | |
if ($exp > $currentTimestamp) { | |
unset($this->usedJwts[$jti]); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment