PHPackages                             per-seo/psr-jwt - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. per-seo/psr-jwt

ActiveLibrary[HTTP &amp; Networking](/categories/http)

per-seo/psr-jwt
===============

A PSR 7 compliant JSON Web Token Middleware Library.

1.0(3mo ago)04MITPHPPHP &gt;=7.4.0CI failing

Since Feb 4Pushed 3mo agoCompare

[ Source](https://github.com/per-seo/psr-jwt)[ Packagist](https://packagist.org/packages/per-seo/psr-jwt)[ RSS](/packages/per-seo-psr-jwt/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (13)Versions (2)Used By (0)

PSR Compliant JSON Web Token Middleware
=======================================

[](#psr-compliant-json-web-token-middleware)

[![Build Status](https://camo.githubusercontent.com/45242a8d26e8842e6ae80712de3a70f6939583c4dd0aa42644b01f80e6b15fef/68747470733a2f2f7472617669732d63692e6f72672f526f624457616c6c65722f7073722d6a77742e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/RobDWaller/psr-jwt) [![codecov](https://camo.githubusercontent.com/9136ebb49792b2c43d86744d2389142ba6ffdfa2d71ff6f7fb0ca471c987b029/68747470733a2f2f636f6465636f762e696f2f67682f526f624457616c6c65722f7073722d6a77742f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/RobDWaller/psr-jwt) [![Infection MSI](https://camo.githubusercontent.com/96147489fb39ae9bbcb793d08b222fe21b2eb544c34ef87b28c745c7253772a0/68747470733a2f2f62616467652e737472796b65722d6d757461746f722e696f2f6769746875622e636f6d2f526f624457616c6c65722f7073722d6a77742f6d6173746572)](https://infection.github.io) [![StyleCI](https://camo.githubusercontent.com/ec42290744f51c5247a094d0f4d5974e5f227146dff45f3571816d20d5cbaba8/68747470733a2f2f6769746875622e7374796c6563692e696f2f7265706f732f3136373531313638322f736869656c643f6272616e63683d6d6173746572)](https://github.styleci.io/repos/167511682) [![Latest Stable Version](https://camo.githubusercontent.com/79cc071c23826bb900c52a2c7e6b45130b4b51b275f9f9376ba27e83d000a5e5/68747470733a2f2f706f7365722e707567782e6f72672f726264776c6c722f7073722d6a77742f762f737461626c65)](https://packagist.org/packages/rbdwllr/psr-jwt) [![PHP Version Support](https://camo.githubusercontent.com/d44b3b40387e757004e25c39f41dcfc9338373dc07d7709e260a8a562ad3abae/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f726264776c6c722f7073722d6a7774)](https://camo.githubusercontent.com/d44b3b40387e757004e25c39f41dcfc9338373dc07d7709e260a8a562ad3abae/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f726264776c6c722f7073722d6a7774) [![Total Downloads](https://camo.githubusercontent.com/4159432c069908cb4740f6c50a165df0d7382aa1d9e865ba35eee98e4dc789d9/68747470733a2f2f706f7365722e707567782e6f72672f726264776c6c722f7073722d6a77742f646f776e6c6f616473)](https://packagist.org/packages/rbdwllr/psr-jwt)

PSR-JWT is a middleware library which allows you to authorise JSON Web Tokens contained in a web request. It is [PSR-7](https://www.php-fig.org/psr/psr-7/) and [PSR-15](https://www.php-fig.org/psr/psr-15/) compliant and built on top of [ReallySimpleJWT](https://github.com/RobDWaller/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](http://www.slimframework.com/).

For more information on JSON Web Tokens please read [RFC 7519](https://tools.ietf.org/html/rfc7519). Also to learn more about how to pass JSON Web Tokens to web applications please read up on bearer token authorisation in [RFC 6750](https://tools.ietf.org/html/rfc6750).

Contents
--------

[](#contents)

- [Setup](#setup)
- [Basic Usage](#basic-usage)
    - [Slim PHP Example Implementation](#slim-php-example-implementation)
    - [Generate JSON Web Token](#generate-json-web-token)
    - [Parse and Validate JSON Web Token](#parse-and-validate-json-web-token)
    - [Retrieve Token From Request](#retrieve-token-from-request)
- [Advanced Usage](#advanced-usage)
    - [Handlers](#handlers)
    - [Create Custom Handler](#create-custom-handler)

Setup
-----

[](#setup)

To install this package you will need to install [Composer](https://getcomposer.org/) 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 per-seo/psr-jwt
```

**Install via the composer.json file:**

```
"require": {
    "per-seo/psr-jwt": "^1.0"
}
```

Basic Usage
-----------

[](#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, `Authorisation Failed!`.

### Slim PHP Example Implementation

[](#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

[](#generate-json-web-token)

To generate JSON Web Tokens PsrJwt offers a wrapper for the library [ReallySimpleJWT](https://github.com/RobDWaller/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

[](#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](https://github.com/RobDWaller/ReallySimpleJWT/blob/master/readme.md) documentation.

### Retrieve Token From Request

[](#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
--------------

[](#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

[](#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

[](#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](https://www.php-fig.org/psr/psr-15/). 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
-------

[](#license)

MIT

Author
------

[](#author)

Rob Waller

Twitter: [@robdwaller](https://twitter.com/RobDWaller)

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance82

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity34

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

94d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ecae5115f6d76e2f46591e8ca95e77dec5345dfdff31734b4d3e12d9a17930b6?d=identicon)[BrainStormDevel](/maintainers/BrainStormDevel)

---

Top Contributors

[![BrainStormDevel](https://avatars.githubusercontent.com/u/23012973?v=4)](https://github.com/BrainStormDevel "BrainStormDevel (1 commits)")

---

Tags

psr-7phpjwtjsontokensAuthenticationauthorisationjson web tokens

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/per-seo-psr-jwt/health.svg)

```
[![Health](https://phpackages.com/badges/per-seo-psr-jwt/health.svg)](https://phpackages.com/packages/per-seo-psr-jwt)
```

###  Alternatives

[rbdwllr/psr-jwt

A PSR 7 compliant JSON Web Token Middleware Library.

1658.0k7](/packages/rbdwllr-psr-jwt)[rbdwllr/reallysimplejwt

A really simple library to generate user authentication JSON Web Tokens.

2902.4M22](/packages/rbdwllr-reallysimplejwt)[jimtools/jwt-auth

PSR-15 JWT Authentication middleware, A replacement for tuupola/slim-jwt-auth

20142.3k3](/packages/jimtools-jwt-auth)[mezzio/mezzio-authentication-oauth2

OAuth2 (server) authentication middleware for Mezzio and PSR-7 applications.

28483.0k2](/packages/mezzio-mezzio-authentication-oauth2)[mezzio/mezzio-authentication

Authentication middleware for Mezzio and PSR-7 applications

121.6M26](/packages/mezzio-mezzio-authentication)[genkgo/archive-stream

Stream a ZIP file (memory efficient) as a PSR-7 message

3063.0k](/packages/genkgo-archive-stream)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
