rbdwllr / psr-jwt
A PSR 7 compliant JSON Web Token Middleware Library.
Installs: 39 316
Dependents: 7
Suggesters: 0
Security: 0
Stars: 15
Watchers: 1
Forks: 5
Open Issues: 4
Requires
- php: >=8.0.0
- nyholm/psr7: ^1.5
- psr/http-message: ^1.0
- psr/http-server-middleware: ^1.0
- rbdwllr/reallysimplejwt: ^5.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.8
- infection/infection: ^0.26
- phploc/phploc: ^7.0
- phpmd/phpmd: ^2.12
- phpstan/phpstan: ^1.7
- phpunit/phpunit: ^9.5
- sebastian/phpcpd: ^6.0
- squizlabs/php_codesniffer: ^3.6
This package is auto-updated.
Last update: 2024-12-12 16:15:33 UTC
README
PSR-JWT is a middleware library which allows you to authorise JSON Web Tokens contained in a web request. It is PSR-7 and PSR-15 compliant and built on top of ReallySimpleJWT.
The library also allows you to generate JSON Web Tokens and the PSR-7 / PSR-15 compliant middleware can be added to any compatible framework, such as Slim PHP.
For more information on JSON Web Tokens please read RFC 7519. Also to learn more about how to pass JSON Web Tokens to web applications please read up on bearer token authorisation in RFC 6750.
Contents
Setup
To install this package you will need to install Composer and then run composer init
. Once this is done you can install the package via the command line or by editing the composer.json file created by the composer init
command.
Finally you will need to reference the Composer autoloader in your PHP code, require 'vendor/autoload.php';
. The location of the autoload file will differ dependent on where your code is run. Note, some frameworks already have the autoload file referenced for you.
Install via Composer on the command line:
composer require rbdwllr/psr-jwt
Install via the composer.json file:
"require": { "rbdwllr/psr-jwt": "^0.3" }
Basic Usage
PsrJwt can be used with any PSR-7 / PSR-15 compliant framework. Just call one of the middleware factory methods and they will return a middleware instance that exposes two methods, __invoke()
and process()
. The latter will work with PSR-15 compliant frameworks and the former will work with older PSR-7 compliant frameworks.
// Will generate a text/html response if JWT authorisation fails. \PsrJwt\Factory\JwtMiddleware::html('secret', 'tokenKey', 'body'); // Will generate an application/json response if JWT authorisation fails. \PsrJwt\Factory\JwtMiddleware::json('secret', 'tokenKey', ['body']);
Secret: is the string required to hash the JSON Web Token signature.
Token Key: is the key required to retrieve the JSON Web Token from a cookie, query parameter or the request body. By default though the library looks for tokens in the bearer field of the authorization header. If you use the bearer field you can pass an empty string for the token key ''
.
Body: is the body content you would like to return in the response if authorisation fails. For example, <h1>Authorisation Failed!</h1>
.
Slim PHP Example Implementation
To add the middleware to a route in Slim PHP you can use the code below.
// Can be added to any routes file in Slim, often index.php. require '../../vendor/autoload.php'; $app->get('/jwt', function (Request $request, Response $response) { $response->getBody()->write("JSON Web Token is Valid!"); return $response; })->add(\PsrJwt\Factory\JwtMiddleware::html('Secret123!456$', 'jwt', 'Authorisation Failed'));
Generate JSON Web Token
To generate JSON Web Tokens PsrJwt offers a wrapper for the library ReallySimpleJWT. You can create an instance of the ReallySimpleJWT builder by calling the built in factory method.
require 'vendor/autoload.php'; $factory = new \PsrJwt\Factory\Jwt(); $builder = $factory->builder(); $token = $builder->setSecret('!secReT$123*') ->setPayloadClaim('uid', 12) ->build(); echo $token->getToken();
Parse and Validate JSON Web Token
If for some reason you need to parse or validate a token outside of the normal middleware authorisation flow the JWT factory class provides a parser method.
This will return an instance of the Really Simple JWT Parse class which provides token parsing and validation functionality.
require 'vendor/autoload.php'; $factory = new \PsrJwt\Factory\Jwt(); $parser = $factory->parser('token', 'secret'); $parser->validate(); $parsed = $parser->parse(); var_dump($parsed->getPayload());
For more information on creating, parsing and validating tokens please read the ReallySimpleJWT documentation.
Retrieve Token From Request
If you would like to retrieve the JSON Web Token from the request outside of the normal middleware authorisation flow you can use the request helper class.
It allows you to retrieve the token itself or just access the token's payload or header.
require 'vendor/autoload.php'; use PsrJwt\Helper\Request; $helper = new Request(); // Will return a ReallySimpleJWT Parsed object. $helper->getParsedToken($request, $tokenKey); // Return the token header as an array. $helper->getTokenHeader($request, $tokenKey); // Return the token payload as an array. $helper->getTokenPayload($request, $tokenKey);
Advanced Usage
You don't have to use the factory methods explained above to generate the JWT authorisation middleware you can instantiate all the required classes directly. This allows you to configure a custom setup.
use PsrJwt\Handler\Html; use PsrJwt\JwtAuthMiddleware; $htmlHandler = new Html($secret, $tokenKey, $body); $middleware = new JwtAuthMiddleware($htmlHandler);
Handlers
PsrJwt is built to work with any PSR-15 compliant handler. As standard it comes with two built in handlers, one which returns text/html responses and another which returns application/json responses.
You can use these handlers simply by instantiating them and passing them to the PsrJwt middleware.
// Create Middleware with JSON handler. use PsrJwt\Handler\Json; use PsrJwt\JwtAuthMiddleware; // The handler. $jsonHandler = new Json($secret, $tokenKey, $body); // The middleware. $middleware = new JwtAuthMiddleware($jsonHandler);
Create Custom Handler
To create your own handler you need to do two things. First create a class which implements the Psr\Http\Server\RequestHandlerInterface
interface. This requires you create a handle()
method which consumes a Psr\Http\Message\ServerRequestInterface
object and returns a Psr\Http\Message\ResponseInterface
object.
Next you will need to extend the PsrJwt\Auth\Authorise
class as this will give you access to the JSON Web Token authorisation functionality. Once this is done you will be able to pass your handler to the PsrJwt\JwtAuthMiddleware
class and then integrate it with your desired framework.
// An example JWT Authorisation Handler. use PsrJwt\Auth\Authorise; use PsrJwt\JwtAuthMiddleware; use Psr\Http\Server\RequestHandlerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Nyholm\Psr7\Response; class MyHandler extends Authorise implements RequestHandlerInterface { public function __construct(string $secret, string $tokenKey) { parent::__construct($secret, $tokenKey); } public function handle(ServerRequestInterface $request): ResponseInterface { $auth = $this->authorise($request); return new Response( $auth->getCode(), [], 'The Response Body', '1.1', $auth->getMessage() ); } } // Add Handler to Middleware. $middleware = new JwtAuthMiddleware(new MyHandler('secret', 'token-key')); // Add Middleware to Slim PHP route. $app->get('/my/route', function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("OK!"); return $response; })->add($middleware);
License
MIT
Author
Rob Waller
Twitter: @robdwaller