• This repository has been archived on 11/Sep/2024
  • Stars
    star
    828
  • Rank 55,086 (Top 2 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 9 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PSR-7 and PSR-15 JWT Authentication Middleware

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.

Latest Version Packagist Software License Build Status Coverage

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.

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.

For example implementation see Slim API Skeleton.

Install

Install latest version using composer.

$ composer require tuupola/slim-jwt-auth

If using Apache add the following to the .htaccess file. Otherwise PHP wont have access to Authorization: Bearer header.

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.

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.

$app = new Slim\App;

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

An example where your secret is stored as an environment variable:

$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.

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.

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.

$app = new Slim\App;

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

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.

$app = new Slim\App;

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

Header

By default middleware tries to find the token from Authorization header. You can change header name using the header parameter.

$app = new Slim\App;

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

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.

$app = new Slim\App;

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

Cookie

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.

$app = new Slim\App;

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

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.

$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

$app = new Slim\App;

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

/* ... */

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

Logger

The optional logger parameter allows you to pass in a PSR-3 compatible logger to help with debugging or other application logging needs.

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.

$app = new Slim\App;

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

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.

$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.

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.

$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.

By default middleware configuration looks like this. All paths are authenticated with all request methods except OPTIONS.

$app = new Slim\App;

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

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.

$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.

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

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.

[
    "iat" => "1428819941",
    "exp" => "1744352741",
    "scope" => ["read", "write", "delete"]
]
$app = new Slim\App;

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

$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);
    }
});

Testing

You can run tests either manually or automatically on every code change. Automatic tests require entr to work.

$ make test
$ brew install entr
$ make watch

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

License

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

More Repositories

1

lazyload

Vanilla JavaScript plugin for lazyloading images
JavaScript
8,761
star
2

jquery_chained

Chained Selects for jQuery and Zepto
JavaScript
589
star
3

slim-basic-auth

PSR-7 and PSR-15 HTTP Basic Authentication Middleware
PHP
440
star
4

slim-api-skeleton

Slim 3 API skeleton project for Composer
PHP
312
star
5

hagl

Hardware Agnostic Graphics Library for embedded
C
309
star
6

jquery_viewport

Add viewport selectors to jQuery. For example $("img:below-the-fold").something()
HTML
256
star
7

branca-spec

Authenticated and encrypted API tokens using modern crypto
223
star
8

server-timing-middleware

PSR-7 & PSR-15 middleware to add the Server-Timing header
PHP
198
star
9

base62

Base62 encoder and decoder for arbitrary data
PHP
195
star
10

micropython-mpu9250

MicroPython I2C driver for MPU9250 9-axis motion tracking device
Python
146
star
11

cors-middleware

PSR-7 and PSR-15 CORS middleware
PHP
132
star
12

ksuid

K-Sortable Globally Unique IDs for PHP
PHP
103
star
13

branca-js

Authenticated encrypted API Tokens for JavaScript.
JavaScript
94
star
14

php_google_maps

API to help working with Google Static Maps.
PHP
84
star
15

micropython-m5stack

MicroPython Kitchen Sink for M5Stack
Python
81
star
16

avr_demo

Atmel demo code. Does not use any Arduino libraries. I want to learn this the hard way (tm).
Makefile
80
star
17

slim-image-resize

Image Resize Middleware for Slim Framework
PHP
60
star
18

branca-php

Authenticated and encrypted API tokens using modern crypto
PHP
52
star
19

base58

Base58 encoder and decoder for arbitrary data
PHP
51
star
20

esp_video

Proof of concept video player for ESP32 boards
C
48
star
21

hagl_esp_mipi

ESP32 MIPI DCS abstraction layer for the HAGL graphics library
C
48
star
22

pybranca

Authenticated Encrypted API Tokens for Python.
Python
47
star
23

instrument

PHP application instrumentation toolkit
PHP
44
star
24

hagl_pico_mipi

Raspberry Pi Pico MIPI DCS absraction layer for the HAGL graphics library
C
44
star
25

esp_effects

Old school demo effects for ESP32
C
42
star
26

whereami

Common PHP interface for wifi positioning services
PHP
34
star
27

slim-facebook

Boilerplate Facebook application with Slim, Eloquent and Facebook API.
JavaScript
33
star
28

demo_code

Miscallenous demo code.
JavaScript
32
star
29

axp192

Platform agnostic I2C driver for AXP192 power system management IC
C
31
star
30

esp_examples

The mandatory ESP-IDF (ESP32) examples repository
C
30
star
31

jquery_filestyle

jQuery plugin for styling file input elements.
JavaScript
28
star
32

base85

Base85 encoder and decoder for arbitrary data
PHP
27
star
33

jquery_dictionary

Spotlight searchable offline jQuery API documentation for OS X.
25
star
34

trilateration

Trilateration for PHP
PHP
24
star
35

pico_effects

Old school demo effects for Raspberry Pi Pico
C
23
star
36

pcf8563

Platform agnostic I2C driver for PCF8563 RTC
C
22
star
37

esp_software_i2c

Software I2C driver for ESP-IDF (ESP32)
C
22
star
38

witchcraft

Opionated PHP magic methods as traits for PHP 5.4+
PHP
21
star
39

micropython-mpu6886

MicroPython I2C driver for MPU6886 6-axis motion tracking device
Python
20
star
40

micropython-ili934x

MicroPython SPI Driver for ILI934X Series Based TFT / LCD Displays
Python
18
star
41

http-factory

Lightweight autodiscovering PSR-17 HTTP factories
PHP
17
star
42

wolf_assets

Mephisto style assets management for Wolf CMS. This plugin is currently unmaintained. Let me know if you want to take over.
PHP
17
star
43

php-docker-k8s

Examples how to run PHP with Docker and Kubernetes
PHP
16
star
44

flat-ui-theme

Flat UI theme for TextMate 2 and Sublime Text
15
star
45

sdl2_effects

Old school demo effects with HAGL and SDL2
C
14
star
46

embedded-fonts

FONTX fonts for embedded projects
C
14
star
47

base32

Base32 encoder and decoder for arbitrary data
PHP
13
star
48

instrument-middleware

PSR-7 Middleware for instrumenting PHP applications
PHP
11
star
49

slim-todo-backend

Slim 3 + Spot example for todobackend.com
PHP
11
star
50

slim-skeleton

Slim 3 + Datamapper + Monolog + Plates project for Composer
PHP
11
star
51

callable-handler

Compatibility layer between PSR-7 double pass and PSR-15 middlewares
PHP
10
star
52

bm8563

Platform agnostic I2C driver for BM8563 RTC
C
9
star
53

hagl_sdl2

SDL2 abstraction layer for the HAGL graphics library
C
9
star
54

branca-middleware

PSR-7 and PSR-15 Branca token authentication middleware
PHP
9
star
55

micropython-examples

The mandatory various experiments with MicroPython repository
Python
9
star
56

micropython-lis2hh12

MicroPython I2C driver for LIS2HH12 3-axis accelerometer
Python
9
star
57

wolf_dashboard

Provides simple admin dashboard to Wolf CMS.
PHP
9
star
58

branca-elixir

Secure alternative to JWT. Authenticated encrypted API tokens for Elixir.
Elixir
8
star
59

frog_jquery

Add jQuery to Frog CMS admin interface.
PHP
8
star
60

jquery_jeditable_wysiwyg

Wysiwyg input for Jeditable.
JavaScript
8
star
61

wolf_funky_cache

Funky cache plugin for Wolf CMS
PHP
7
star
62

beeper

Generic paginator for PHP 7.1+
PHP
7
star
63

jquery_jeditable_markitup

Universal markup editor for Jeditable.
7
star
64

axp173

Platform agnostic I2C driver for AXP173 power system management IC
C
6
star
65

triple-a

Alternative AVR (Arduino) Library
C
6
star
66

esp_gfx

HAGL speed tests for ESP32 boards
C
6
star
67

axp202

Platform agnostic I2C driver for AXP202 PMU
C
6
star
68

wolf_first_child

Redirect to first child page behaviour for Wolf CMS.
PHP
6
star
69

php_record

Simple Active Record implementation in PHP.
PHP
6
star
70

esp_twatch2020

Kitchen sink project for T-Watch 2020 and ESP-IDF
C
6
star
71

micropython-gnssl76l

MicroPython I2C driver for Quectel GNSS L76-L (GPS)
Python
6
star
72

rack-facebook-method-fix

Rack middleware to fix Facebook always POST problem.
Ruby
6
star
73

rack-funky-cache

Funky caching for Rack based applications
Ruby
5
star
74

frog_email_template

Provides form mailer backend to Frog CMS. This code is no longer maintained. Please go to: https://github.com/dajare/wolf_email_template
PHP
5
star
75

mephisto_sitemap

Mephisto plugin which implements (Google, MSN, Yahoo ) Sitemap protocol.
Ruby
5
star
76

trytes

Trytes encoder and decoder for arbitrary data
PHP
4
star
77

wolf_jquery_ui

Add jQuery UI to Wolf CMS admin interface.
PHP
4
star
78

em-websocket-server

Simple websocket server with EventMachine
Ruby
4
star
79

esp_i2c_helper

ESP I2C master HAL for hardware agnostic I2C drivers
C
4
star
80

screenshot

Full size website screenshots with Sinatra.
JavaScript
4
star
81

pico_gfx

HAGL speed tests for Rasrpberry Pi Pico boards
C
4
star
82

hagl_esp_solomon

ESP32 Solomon HAL for the HAGL graphics library
C
4
star
83

esp_mipi

Low level MIPI DCS compatible display driver for ESP-IDF
C
4
star
84

hagl_gd

GD HAL for the HAGL graphics library
C
3
star
85

fontx_tools

C
3
star
86

gd32v_effects

Old school demo effects for GD32V
C
3
star
87

slim-fake-mcrypt

Fake PHP mcrypt extension to enable installing Slim 2.3.* with Composer
3
star
88

dbal-psr3-logger

PSR-3 Logger for Doctrine DBAL
PHP
3
star
89

ulid

Universally Unique Lexicographically Sortable Identifier
PHP
3
star
90

corelocation

PHP implementation of Apple location services protocol
PHP
3
star
91

rack-lazy-load

Companion Rack middleware for Lazy Load jQuery plugin.
Ruby
2
star
92

hagl_gd32v_mipi

GD32V MIPI DCS HAL for the HAGL graphics library
C
2
star
93

esp_m5stick

Kitchen sink project for M5StickC and ESP-IDF
C
2
star
94

appelsiini.net

Sources and build files for my personal blog.
HTML
2
star
95

madgwick-backup

Backup of Sebastian Madgwick's original LGPL licensed sensor fusion algorithm
C
2
star
96

branca-cli

Command line tool for encoding, decoding and inspecting Branca tokens
JavaScript
2
star
97

wolf_jquery_tools

Add jQuery Tools to Wolf CMS admin interface.
PHP
2
star
98

arduino_xylophone

Awesome christmas xylophone done with Arduino and Sinatra.
JavaScript
1
star
99

messente

An object-oriented Ruby wrapper for the Messente API.
Ruby
1
star
100

gd32v_gfx

HAGL speed tests for GD32V boards
C
1
star