2017 © Pedro Peláez
 

library slim-jwt-auth

PSR-7 and PSR-15 JWT Authentication Middleware

image

tuupola/slim-jwt-auth

PSR-7 and PSR-15 JWT Authentication Middleware

  • Tuesday, May 29, 2018
  • by tuupola
  • Repository
  • 31 Watchers
  • 474 Stars
  • 210,290 Installations
  • PHP
  • 28 Dependents
  • 1 Suggesters
  • 82 Forks
  • 18 Open issues
  • 37 Versions
  • 17 % Grown

The README.md

[!IMPORTANT] This package is abandoned. See jimtools/jwt-auth for replacement., (*1)

PSR-7 and PSR-15 JWT Authentication Middleware

This middleware implements JSON Web Token Authentication. It was originally developed for Slim but can be used with any framework using PSR-7 and PSR-15 style middlewares. It has been tested with Slim Framework and Zend Expressive., (*2)

Latest Version Packagist Software License Build Status Coverage, (*3)

Heads up! You are reading documentation for 3.x branch which is PHP 7.1 and up only. If you are using older version of PHP see the 2.x branch. These two branches are not backwards compatible, see UPGRADING for instructions how to upgrade., (*4)

Middleware does not implement OAuth 2.0 authorization server nor does it provide ways to generate, issue or store authentication tokens. It only parses and authenticates a token when passed via header or cookie. This is useful for example when you want to use JSON Web Tokens as API keys., (*5)

For example implementation see Slim API Skeleton., (*6)

Install

Install latest version using composer., (*7)

``` bash $ composer require tuupola/slim-jwt-auth, (*8)


If using Apache add the following to the `.htaccess` file. Otherwise PHP wont have access to `Authorization: Bearer` header. ``` bash RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Usage

Configuration options are passed as an array. The only mandatory parameter is secret which is used for verifying the token signature. Note again that secret is not the token. It is the secret you use to sign the token., (*9)

For simplicity's sake examples show secret hardcoded in code. In real life you should store it somewhere else. Good option is environment variable. You can use dotenv or something similar for development. Examples assume you are using Slim Framework., (*10)

``` php $app = new Slim\App;, (*11)

$app->add(new Tuupola\Middleware\JwtAuthentication([ "secret" => "supersecretkeyyoushouldnotcommittogithub" ]));, (*12)


An example where your secret is stored as an environment variable: ``` php $app = new Slim\App; $app->add(new Tuupola\Middleware\JwtAuthentication([ "secret" => getenv("JWT_SECRET") ]));

When a request is made, the middleware tries to validate and decode the token. If a token is not found or there is an error when validating and decoding it, the server will respond with 401 Unauthorized., (*13)

Validation errors are triggered when the token has been tampered with or the token has expired. For all possible validation errors, see JWT library source., (*14)

Optional parameters

Path

The optional path parameter allows you to specify the protected part of your website. It can be either a string or an array. You do not need to specify each URL. Instead think of path setting as a folder. In the example below everything starting with /api will be authenticated. If you do not define path all routes will be protected., (*15)

``` php $app = new Slim\App;, (*16)

$app->add(new Tuupola\Middleware\JwtAuthentication([ "path" => "/api", /* or ["/api", "/admin"] */ "secret" => "supersecretkeyyoushouldnotcommittogithub" ]));, (*17)


### Ignore With optional `ignore` parameter you can make exceptions to `path` parameter. In the example below everything starting with `/api` and `/admin` will be authenticated with the exception of `/api/token` and `/admin/ping` which will not be authenticated. ``` php $app = new Slim\App; $app->add(new Tuupola\Middleware\JwtAuthentication([ "path" => ["/api", "/admin"], "ignore" => ["/api/token", "/admin/ping"], "secret" => "supersecretkeyyoushouldnotcommittogithub" ]));

By default middleware tries to find the token from Authorization header. You can change header name using the header parameter., (*18)

``` php $app = new Slim\App;, (*19)

$app->add(new Tuupola\Middleware\JwtAuthentication([ "header" => "X-Token", "secret" => "supersecretkeyyoushouldnotcommittogithub" ]));, (*20)


### Regexp By default the middleware assumes the value of the header is in `Bearer <token>` format. You can change this behaviour with `regexp` parameter. For example if you have custom header such as `X-Token: <token>` you should pass both header and regexp parameters. ``` php $app = new Slim\App; $app->add(new Tuupola\Middleware\JwtAuthentication([ "header" => "X-Token", "regexp" => "/(.*)/", "secret" => "supersecretkeyyoushouldnotcommittogithub" ]));

If token is not found from neither environment or header, the middleware tries to find it from cookie named token. You can change cookie name using cookie parameter., (*21)

``` php $app = new Slim\App;, (*22)

$app->add(new Tuupola\Middleware\JwtAuthentication([ "cookie" => "nekot", "secret" => "supersecretkeyyoushouldnotcommittogithub" ]));, (*23)


### Algorithm You can set supported algorithms via `algorithm` parameter. This can be either string or array of strings. Default value is `["HS256", "HS512", "HS384"]`. Supported algorithms are `HS256`, `HS384`, `HS512` and `RS256`. Note that enabling both `HS256` and `RS256` is a [security risk](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). ``` php $app = new Slim\App; $app->add(new Tuupola\Middleware\JwtAuthentication([ "secret" => "supersecretkeyyoushouldnotcommittogithub", "algorithm" => ["HS256", "HS384"] ]));

Attribute

When the token is decoded successfully and authentication succeeds the contents of the decoded token is saved as token attribute to the $request object. You can change this with. attribute parameter. Set to null or false to disable this behavour, (*24)

``` php $app = new Slim\App;, (*25)

$app->add(new Tuupola\Middleware\JwtAuthentication([ "attribute" => "jwt", "secret" => "supersecretkeyyoushouldnotcommittogithub" ]));, (*26)

/* ... */, (*27)

$decoded = $request->getAttribute("jwt");, (*28)


### Logger The optional `logger` parameter allows you to pass in a PSR-3 compatible logger to help with debugging or other application logging needs. ``` php use Monolog\Logger; use Monolog\Handler\RotatingFileHandler; $app = new Slim\App; $logger = new Logger("slim"); $rotating = new RotatingFileHandler(__DIR__ . "/logs/slim.log", 0, Logger::DEBUG); $logger->pushHandler($rotating); $app->add(new Tuupola\Middleware\JwtAuthentication([ "path" => "/api", "logger" => $logger, "secret" => "supersecretkeyyoushouldnotcommittogithub" ]));

Before

Before function is called only when authentication succeeds but before the next incoming middleware is called. You can use this to alter the request before passing it to the next incoming middleware in the stack. If it returns anything else than Psr\Http\Message\ServerRequestInterface the return value will be ignored., (*29)

``` php $app = new Slim\App;, (*30)

$app->add(new Tuupola\Middleware\JwtAuthentication([ "secret" => "supersecretkeyyoushouldnotcommittogithub", "before" => function ($request, $arguments) { return $request->withAttribute("test", "test"); } ]));, (*31)


### After After function is called only when authentication succeeds and after the incoming middleware stack has been called. You can use this to alter the response before passing it next outgoing middleware in the stack. If it returns anything else than `Psr\Http\Message\ResponseInterface` the return value will be ignored. ``` php $app = new Slim\App; $app->add(new Tuupola\Middleware\JwtAuthentication([ "secret" => "supersecretkeyyoushouldnotcommittogithub", "after" => function ($response, $arguments) { return $response->withHeader("X-Brawndo", "plants crave"); } ]));

Note that both the after and before callback functions receive the raw token string as well as the decoded claims through the $arguments argument., (*32)

Error

Error is called when authentication fails. It receives last error message in arguments. You can use this for example to return JSON formatted error responses., (*33)

$app = new Slim\App;

$app->add(new Tuupola\Middleware\JwtAuthentication([
    "secret" => "supersecretkeyyoushouldnotcommittogithub",
    "error" => function ($response, $arguments) {
        $data["status"] = "error";
        $data["message"] = $arguments["message"];

        $response->getBody()->write(
            json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
        );

        return $response->withHeader("Content-Type", "application/json")
    }
]));

Rules

The optional rules parameter allows you to pass in rules which define whether the request should be authenticated or not. A rule is a callable which receives the request as parameter. If any of the rules returns boolean false the request will not be authenticated., (*34)

By default middleware configuration looks like this. All paths are authenticated with all request methods except OPTIONS., (*35)

``` php $app = new Slim\App;, (*36)

$app->add(new Tuupola\Middleware\JwtAuthentication([ "rules" => [ new Tuupola\Middleware\JwtAuthentication\RequestPathRule([ "path" => "/", "ignore" => [] ]), new Tuupola\Middleware\JwtAuthentication\RequestMethodRule([ "ignore" => ["OPTIONS"] ]) ] ]));, (*37)


RequestPathRule contains both a `path` parameter and a `ignore` parameter. Latter contains paths which should not be authenticated. RequestMethodRule contains `ignore` parameter of request methods which also should not be authenticated. Think of `ignore` as a whitelist. 99% of the cases you do not need to use the `rules` parameter. It is only provided for special cases when defaults do not suffice. ## Security JSON Web Tokens are essentially passwords. You should treat them as such and you should always use HTTPS. If the middleware detects insecure usage over HTTP it will throw a `RuntimeException`. By default this rule is relaxed for requests to server running on `localhost`. To allow insecure usage you must enable it manually by setting `secure` to `false`. ``` php $app->add(new Tuupola\Middleware\JwtAuthentication([ "secure" => false, "secret" => "supersecretkeyyoushouldnotcommittogithub" ]));

Alternatively you could list multiple development servers to have relaxed security. With below settings both localhost and dev.example.com allow incoming unencrypted requests., (*38)

``` php $app->add(new Tuupola\Middleware\JwtAuthentication([ "secure" => true, "relaxed" => ["localhost", "dev.example.com"], "secret" => "supersecretkeyyoushouldnotcommittogithub" ]));, (*39)


## Authorization By default middleware only authenticates. This is not very interesting. Beauty of JWT is you can pass extra data in the token. This data can include for example scope which can be used for authorization. **It is up to you to implement how token data is stored or possible authorization implemented.** Let assume you have token which includes data for scope. By default middleware saves the contents of the token to `token` attribute of the request. ``` php [ "iat" => "1428819941", "exp" => "1744352741", "scope" => ["read", "write", "delete"] ]

``` php $app = new Slim\App;, (*40)

$app->add(new Tuupola\Middleware\JwtAuthentication([ "secret" => "supersecretkeyyoushouldnotcommittogithub" ]));, (*41)

$app->delete("/item/{id}", function ($request, $response, $arguments) { $token = $request->getAttribute("token"); if (in_array("delete", $token["scope"])) { /* Code for deleting item / } else { / No scope so respond with 401 Unauthorized */ return $response->withStatus(401); } });, (*42)


## Testing You can run tests either manually or automatically on every code change. Automatic tests require [entr](http://entrproject.org/) to work. ``` bash $ make test

bash $ brew install entr $ make watch, (*43)

Contributing

Please see CONTRIBUTING for details., (*44)

Security

If you discover any security related issues, please email tuupola@appelsiini.net instead of using the issue tracker., (*45)

License

The MIT License (MIT). Please see License File for more information., (*46)

The Versions

03/04 2018
12/07 2017
27/02 2017

1.x-dev

1.9999999.9999999.9999999-dev https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

27/02 2017

1.0.4

1.0.4.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

27/02 2017

2.3.2

2.3.2.0 https://github.com/tuupola/slim-jwt-auth

PSR-7 JWT Authentication Middleware

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware psr-7 json auth jwt

12/08 2016

1.0.3

1.0.3.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

12/08 2016

2.3.1

2.3.1.0 https://github.com/tuupola/slim-jwt-auth

PSR-7 JWT Authentication Middleware

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware psr-7 json auth jwt

10/05 2016

2.3.0

2.3.0.0 https://github.com/tuupola/slim-jwt-auth

PSR-7 JWT Authentication Middleware

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware psr-7 json auth jwt slim

24/04 2016

2.2.0

2.2.0.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware psr-7 json auth jwt slim

19/03 2016

2.1.0

2.1.0.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

30/01 2016

2.0.3

2.0.3.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

10/12 2015

2.0.2

2.0.2.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

15/11 2015

1.0.2

1.0.2.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

27/10 2015

2.0.1

2.0.1.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

01/10 2015

2.0.0

2.0.0.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

01/10 2015

1.0.1

1.0.1.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

16/09 2015

1.0.0

1.0.0.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

12/07 2015

0.4.0

0.4.0.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

15/05 2015

0.3.0

0.3.0.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

06/05 2015

0.2.1

0.2.1.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

19/04 2015

0.2.0

0.2.0.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

12/04 2015

0.1.1

0.1.1.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim

12/04 2015

0.1.0

0.1.0.0 https://github.com/tuupola/slim-jwt-auth

JSON Web Token Authorization Middleware for Slim Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

middleware json auth jwt slim