jonnybarnes.uk/app/Services/TokenService.php

56 lines
1.3 KiB
PHP
Raw Normal View History

2016-05-19 15:01:28 +01:00
<?php
declare(strict_types=1);
2016-05-19 15:01:28 +01:00
namespace App\Services;
use RuntimeException;
use Lcobucci\JWT\Token;
2016-05-19 15:01:28 +01:00
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Builder;
use InvalidArgumentException;
use Lcobucci\JWT\Signer\Hmac\Sha256;
class TokenService
{
/**
* Generate a JWT token.
*
* @param array The data to be encoded
* @return string The signed token
*/
public function getNewToken(array $data): string
{
$signer = new Sha256();
$token = (new Builder())->set('me', $data['me'])
->set('client_id', $data['client_id'])
->set('scope', $data['scope'])
->set('date_issued', time())
->set('nonce', bin2hex(random_bytes(8)))
->sign($signer, config('app.key'))
2016-05-19 15:01:28 +01:00
->getToken();
return (string) $token;
2016-05-19 15:01:28 +01:00
}
/**
* Check the token signature is valid.
*
* @param string The token
* @return mixed
*/
public function validateToken(string $token): ?Token
2016-05-19 15:01:28 +01:00
{
$signer = new Sha256();
try {
$token = (new Parser())->parse((string) $token);
} catch (InvalidArgumentException | RuntimeException $e) {
return null;
2016-05-19 15:01:28 +01:00
}
if ($token->verify($signer, config('app.key'))) {
2016-05-19 15:01:28 +01:00
//signuture valid
return $token;
}
}
}