Skip to content

Instantly share code, notes, and snippets.

@thedava
Last active November 4, 2018 20:49
Show Gist options
  • Save thedava/0fade9bac8efb8843ff7c77ca59e1e9c to your computer and use it in GitHub Desktop.
Save thedava/0fade9bac8efb8843ff7c77ca59e1e9c to your computer and use it in GitHub Desktop.
PHP JWT example
<?php
use \DateTime;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha512;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\ValidationData;
class JwtUtils
{
const CLAIM_ISSUER = '---';
const CLAIM_SUBJECT = '---';
const CLAIM_ID = '---';
/**
* @return Sha512
*/
private static function getSigner()
{
return new Sha512();
}
/**
* @return Key
*/
private static function getKey()
{
return new Key('---');
}
/**
* @param string $audience
* @param array $data
* @param DateTime $expirationDate
*
* @return string
*
* @throws \Exception
*/
public static function createToken($audience, array $data, DateTime $expirationDate)
{
$now = new DateTime();
$builder = (new Builder())
->setId(self::CLAIM_ID)
->setIssuer(self::CLAIM_ISSUER)
->setAudience($audience)
->setSubject(self::CLAIM_SUBJECT)
->setIssuedAt($now->getTimestamp())
->setNotBefore($now->getTimestamp())
->setExpiration($expirationDate->getTimestamp());
// Add custom claims
foreach ($data as $key => $value) {
$builder->set($key, $value);
}
$token = $builder
->sign(self::getSigner(), self::getKey())
->getToken();
return (string)$token;
}
/**
* @param string $tokenString
*
* @return \Lcobucci\JWT\Token|null
*/
public static function validateToken($tokenString)
{
try {
$token = (new Parser())->parse($tokenString);
if (!$token->isExpired() && $token->verify(self::getSigner(), self::getKey()->getContent())) {
$validation = new ValidationData();
$validation->setIssuer(self::CLAIM_ISSUER);
$validation->setSubject(self::CLAIM_SUBJECT);
$validation->setId(self::CLAIM_ID);
if ($token->validate($validation)) {
return $token;
}
}
return null;
} catch (\Exception $e) {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment