A simple framework-agnostic JSON Web Token authentication solution.
Licensed under MIT. Totally free for private or commercial projects.
composer require andrewdyer/jwt-auth
// Create a new auth provider instance
$authProvider = new App\Providers\AuthProvider();
// Create a new jwt provider instance
$jwtProvider = new App\Providers\JwtProvider();
// Build up jwt claims
$claimsFactory = new Anddye\JwtAuth\ClaimsFactory::build([
'exp' => 1582243200, // Friday, 21 February 2020 00:00:00
'iat' => 1582193571, // Thursday, 20 February 2020 10:12:51
'iss' => 'https://example.com',
'jti' => 'fVcx9BJHqh',
'nbj' => '1582193571', // Thursday, 20 February 2020 10:12:51
]);
// Bring everything together to create a jwt auth instance
$jwtAuth = new JwtAuth($authProvider, $jwtProvider, $claimsFactory);
namespace App\Providers;
use Anddye\JwtAuth\Providers\AuthProviderInterface;
class AuthProvider implements AuthProviderInterface
{
public function byCredentials(string $username, string $password)
{
// TODO: Validate username / password and return an instance of `Anddye\JwtAuth\Contracts\JwtSubject`
}
public function byId(int $id)
{
// TODO: Find a user by id and return an instance of `Anddye\JwtAuth\Contracts\JwtSubject` if exists
}
}
namespace Anddye\JwtAuth\Tests\Stubs\Providers;
use Anddye\JwtAuth\Providers\JwtProviderInterface;
class JwtProvider implements JwtProviderInterface
{
public function decode(string $token)
{
// TODO: Decode JWT token somehow
}
public function encode(array $claims): string
{
// TODO: Encode claims and create a JWT token somehow
}
}
Option | Type | Description |
---|---|---|
exp | int | Time after which the JWT expires. |
iat | int | Time at which the JWT was issued. |
iss | string | Issuer of the JWT. |
jti | string | Unique identifier; can be used to prevent the JWT from being replayed. |
nbj | int | Time before which the JWT must not be accepted for processing. |
$claimsFactory = new Anddye\JwtAuth\ClaimsFactory();
$claimsFactory->setExp(1582243200); // Friday, 21 February 2020 00:00:00
$claimsFactory->setIat(1582193571); // Thursday, 20 February 2020 10:12:51
$claimsFactory->setIss('https://example.com');
$claimsFactory->setJti('fVcx9BJHqh');
$claimsFactory->setNbj(1582193571); // Thursday, 20 February 2020 10:12:51
if (!$token = $jwtAuth->attempt($username, $password)) {
// TODO: Handle failed attempt with credentials
} else {
// TODO: Handle successful attempt with credentials
}
if (!$actor = $jwtAuth->authenticate($token)->getActor()) {
// TODO: Handle failed authentication with token
} else {
// TODO: Handle successful authentication with token
}
If you're using this package, I'd love to hear your thoughts! Feel free to contact me on Twitter.
Need to see an example? Check out this tutorial on how to integrate this library into a Slim 3 project.
Found a bug? Please report it using the issue tracker, or better yet, fork the repository and submit a pull request.