Skip to content

Instantly share code, notes, and snippets.

@ConnorVG
Created July 1, 2015 08:28
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ConnorVG/531c9dff2ac001bb2b2d to your computer and use it in GitHub Desktop.
Save ConnorVG/531c9dff2ac001bb2b2d to your computer and use it in GitHub Desktop.
Simple JWT-PHP Wrapper
<?php namespace App\Services\Jwt\Exceptions;
class BeforeValidException extends \UnexpectedValueException { }
<?php namespace App\Services\Jwt\Exceptions;
class ExpiredException extends \UnexpectedValueException { }
<?php namespace App\Services\Jwt\Exceptions;
class InvalidKeyException extends \UnexpectedValueException { }
<?php
namespace App\Services\Jwt;
use JWT;
use App\Services\Jwt\Exceptions\BeforeValidException;
use App\Services\Jwt\Exceptions\ExpiredException;
use App\Services\Jwt\Exceptions\SignatureInvalidException;
use App\Services\Jwt\Exceptions\InvalidKeyException;
class Manager
{
/**
* The secret.
*
* @var string
*/
protected $secret;
/**
* Constructs the JWT Manager with the configured secret.
*
* @param string|null $secret
*/
public function __construct($secret = null)
{
$this->secret = conf('services.jwt.secret', $secret);
}
/**
* Encodes a payload.
*
* @param array $payload
* @param array|null $scopes
*
* @return string
*/
public function encode($payload = [], $scopes = null)
{
$payload = array_merge($payload, [
'scopes' => is_array($scopes) ? $scopes : config('services.jwt.default_scopes', '*')
]);
return JWT::encode($payload, $this->secret);
}
/**
* Decodes a payload.
*
* @param string $payload
*
* @return array
*/
public function decode($payload)
{
try {
$payload = JWT::decode($payload, $this->secret);
}
catch (\BeforeValidException $e)
{
throw new BeforeValidException;
}
catch (\ExpiredException $e)
{
throw new ExpiredException;
}
catch (\SignatureInvalidException $e)
{
throw new SignatureInvalidException;
}
catch (\Exception $e)
{
throw new InvalidKeyException;
}
return (array) $payload;
}
}
<?php namespace App\Services\Jwt\Exceptions;
class SignatureInvalidException extends \UnexpectedValueException { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment