You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+81-31Lines changed: 81 additions & 31 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,9 +1,9 @@
1
1
# PSR Compliant JSON Web Token Middleware
2
2
[](https://travis-ci.org/RobDWaller/psr-jwt)[](https://codecov.io/gh/RobDWaller/psr-jwt)[](https://infection.github.io)[](https://github.styleci.io/repos/167511682)[](https://packagist.org/packages/rbdwllr/psr-jwt)
3
3
4
-
A [PSR-7](https://www.php-fig.org/psr/psr-7/) and [PSR-15](https://www.php-fig.org/psr/psr-15/) compliant JSON Web Token middleware library built on top of [ReallySimpleJWT](https://github.com/RobDWaller/ReallySimpleJWT).
4
+
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).
5
5
6
-
The library allows you to create JSON Web Tokens and then validate them using PSR-15 compliant middleware which can be added to compatible frameworks such as [Slim PHP](http://www.slimframework.com/) and [Zend Expressive](https://docs.zendframework.com/zend-expressive/).
6
+
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/).
7
7
8
8
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).
9
9
@@ -12,9 +12,9 @@ For more information on JSON Web Tokens please read [RFC 7519](https://tools.iet
12
12
-[Setup](#setup)
13
13
-[Basic Usage](#basic-usage)
14
14
-[Slim PHP Example Implementation](#slim-php-example-implementation)
15
-
-[Zend Expressive Example Implementation](#zend-expressive-example-implementation)
16
-
-[JSON Response Handler](#json-response-handler)
17
15
-[Generate JSON Web Token](#generate-json-web-token)
16
+
-[Parse and Validate JSON Web Token](#parse-and-validate-json-web-token)
17
+
-[Retrieve Token From the Request](retrieve-token-from-the-request)
18
18
-[Advanced Usage](#advanced-usage)
19
19
-[Handlers](#handlers)
20
20
-[Create Custom Handler](#create-custom-handler)
@@ -23,7 +23,7 @@ For more information on JSON Web Tokens please read [RFC 7519](https://tools.iet
23
23
24
24
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.
25
25
26
-
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. Also you will not need to reference the autoload file if you are using a framework like Zend Expressive.
26
+
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.
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 like Zend Expressive and the former will work with older PSR-7 compliant frameworks like Slim PHP v3.
44
+
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.
45
45
46
46
```php
47
-
// Will generate a text/html response if JWT authentication fails.
47
+
// Will generate a text/html response if JWT authorisation fails.
The `secret` is the string required to hash the JSON Web Token signature.
54
+
**Secret:** is the string required to hash the JSON Web Token signature.
55
55
56
-
The `tokenKey` 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.
56
+
**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 `''`.
57
57
58
-
The `body`is the body content you would like to return in the response if authentication fails. For example, `<h1>Authentication Failed!</h1>`.
58
+
**Body:**is the body content you would like to return in the response if authorisation fails. For example, `<h1>Authorisation Failed!</h1>`.
59
59
60
60
### Slim PHP Example Implementation
61
61
62
-
To implement the middleware in Slim PHP 3.0 you can use the code below.
62
+
To add the middleware to a route in Slim PHP you can use the code below.
63
63
64
64
```php
65
65
// Can be added to any routes file in Slim, often index.php.
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.
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.
93
+
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.
94
+
95
+
This will return an instance of the Really Simple JWT Parse class which provides token parsing and validation functionality.
85
96
86
97
```php
87
98
require 'vendor/autoload.php';
88
99
89
-
\PsrJwt\Factory\Jwt::builder();
100
+
$factory = new \PsrJwt\Factory\Jwt();
101
+
102
+
$parser = $factory->parse('token', 'secret');
103
+
104
+
$parser->validate();
105
+
106
+
$parser->parse();
90
107
```
91
108
92
-
For more information on creating tokens please read the [ReallySimpleJWT](https://github.com/RobDWaller/ReallySimpleJWT/blob/master/readme.md) documentation.
109
+
For more information on creating, parsing and validating tokens please read the [ReallySimpleJWT](https://github.com/RobDWaller/ReallySimpleJWT/blob/master/readme.md) documentation.
110
+
111
+
### Retrieve Token From the Request
112
+
113
+
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.
114
+
115
+
It allows you to retrive the token itself or just access the token's payload or header.
116
+
117
+
```php
118
+
require 'vendor/autoload.php';
119
+
120
+
use PsrJwt\Helper\Request;
121
+
122
+
$helper = new Request();
123
+
124
+
// Will return a ReallySimpleJWT Parsed object.
125
+
$helper->getParsedToken($request, $tokenKey);
126
+
127
+
// Return the token header as an array.
128
+
$helper->getTokenHeader($request, $tokenKey);
129
+
130
+
// Return the token payload as an array.
131
+
$helper->getTokenPayload($request, $tokenKey);
132
+
```
93
133
94
134
## Advanced Usage
95
135
96
-
You don't have to use the factory methods explained above to generate the JWT authentication middleware you can call all the required classes directly. This allows you to configure a more customised setup and use your own handlers.
136
+
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.
137
+
138
+
```php
139
+
use PsrJwt\Handler\Html;
140
+
use PsrJwt\JwtAuthMiddleware;
141
+
142
+
$htmlHandler = new Html($secret, $tokenKey, $body);
143
+
144
+
$middleware = new JwtAuthMiddleware($htmlHandler);
145
+
```
97
146
98
147
### Handlers
99
148
100
-
PsrJwt is built to work with any PSR15 compliant handler. As standard it comes with two built in handlers, one which returns text/html responses and another which returns application/json responses.
149
+
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.
101
150
102
151
You can use these handlers simply by instantiating them and passing them to the PsrJwt middleware.
103
152
@@ -106,27 +155,28 @@ You can use these handlers simply by instantiating them and passing them to the
106
155
use PsrJwt\Handler\Json;
107
156
use PsrJwt\JwtAuthMiddleware;
108
157
158
+
// The handler.
159
+
$jsonHandler = new Json($secret, $tokenKey, $body);
109
160
110
-
$auth = new Json($secret, $tokenKey, $body);
111
-
112
-
$middleware = new JwtAuthMiddleware($auth);
161
+
// The middleware.
162
+
$middleware = new JwtAuthMiddleware($jsonHandler);
113
163
```
114
164
115
165
### Create Custom Handler
116
166
117
167
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.
118
168
119
-
Next you will need to extend the `PsrJwt\Auth\Authenticate` class as this will give you access to the JSON Web Token authentication 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.
169
+
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.
120
170
121
171
```php
122
-
// An example JWT Authentication Handler.
123
-
use PsrJwt\Auth\Authenticate;
172
+
// An example JWT Authorisation Handler.
173
+
use PsrJwt\Auth\Authorise;
124
174
use Psr\Http\Server\RequestHandlerInterface;
125
175
use Psr\Http\Message\ResponseInterface;
126
176
use Psr\Http\Message\ServerRequestInterface;
127
177
use Nyholm\Psr7\Response;
128
178
129
-
class MyHandler extends Authenticate implements RequestHandlerInterface
179
+
class MyHandler extends Authorise implements RequestHandlerInterface
130
180
{
131
181
public function __construct(string $secret, string $tokenKey)
132
182
{
@@ -135,7 +185,7 @@ class MyHandler extends Authenticate implements RequestHandlerInterface
135
185
136
186
public function handle(ServerRequestInterface $request): ResponseInterface
0 commit comments