Skip to content

Instantly share code, notes, and snippets.

@RafaelKa
Created February 2, 2016 23:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RafaelKa/5c26957569ef5422ab8e to your computer and use it in GitHub Desktop.
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.
<?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