PHPackages                             tuupola/slim-jwt-auth - 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. tuupola/slim-jwt-auth

Abandoned → [jimtools/jwt-auth](/?search=jimtools%2Fjwt-auth)ArchivedLibrary[HTTP &amp; Networking](/categories/http)

tuupola/slim-jwt-auth
=====================

PSR-7 and PSR-15 JWT Authentication Middleware

3.8.0(2y ago)8222.7M—9%142[17 issues](https://github.com/tuupola/slim-jwt-auth/issues)[6 PRs](https://github.com/tuupola/slim-jwt-auth/pulls)20MITPHPPHP ^7.4|^8.0

Since Apr 12Pushed 1y ago28 watchersCompare

[ Source](https://github.com/tuupola/slim-jwt-auth)[ Packagist](https://packagist.org/packages/tuupola/slim-jwt-auth)[ Docs](https://github.com/tuupola/slim-jwt-auth)[ RSS](/packages/tuupola-slim-jwt-auth/feed)WikiDiscussions 3.x Synced 1mo ago

READMEChangelogDependencies (12)Versions (46)Used By (20)

Important

This package is abandoned. See [jimtools/jwt-auth](https://github.com/JimTools/jwt-auth) for replacement.

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](http://www.slimframework.com/) and [Zend Expressive](https://zendframework.github.io/zend-expressive/).

[![Latest Version](https://camo.githubusercontent.com/7a9e7ef1c60ec2d64b94059ee9597d8e46b30834af7f5ed0607b846797268038/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f747575706f6c612f736c696d2d6a77742d617574682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tuupola/slim-jwt-auth)[![Packagist](https://camo.githubusercontent.com/b19196d83170a956af0b2b6410bcb580c08da87f1062d3017c80436a55b5a97b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f747575706f6c612f736c696d2d6a77742d617574682e737667)](https://packagist.org/packages/tuupola/slim-jwt-auth)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Build Status](https://camo.githubusercontent.com/fddc6d9e8d09d3d9bb4ade10be54da67513c8a7603953d6ef4295e0cc84b647f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f747575706f6c612f736c696d2d6a77742d617574682f74657374732e796d6c3f6272616e63683d332e78267374796c653d666c61742d737175617265)](https://github.com/tuupola/slim-jwt-auth/actions)[![Coverage](https://camo.githubusercontent.com/4b21a785070f0ea5cd6c72ae99f713ff59e46ed766410423241a8a183149cbba/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f747575706f6c612f736c696d2d6a77742d617574682f332e782e7376673f7374796c653d666c61742d737175617265)](https://codecov.io/github/tuupola/slim-jwt-auth/branch/3.x)

Heads up! You are reading documentation for [3.x branch](https://github.com/tuupola/slim-jwt-auth/tree/3.x) which is PHP 7.1 and up only. If you are using older version of PHP see the [2.x branch](https://github.com/tuupola/slim-jwt-auth/tree/2.x). These two branches are not backwards compatible, see [UPGRADING](https://github.com/tuupola/slim-jwt-auth/blob/3.x/UPGRADING.md) 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](https://auth0.com/blog/2014/12/02/using-json-web-tokens-as-api-keys/).

For example implementation see [Slim API Skeleton](https://github.com/tuupola/slim-api-skeleton).

Install
-------

[](#install)

Install latest version using [composer](https://getcomposer.org/).

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

[](#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](https://github.com/vlucas/phpdotenv) 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](https://github.com/firebase/php-jwt/blob/master/src/JWT.php#L60-L138) source.

Optional parameters
-------------------

[](#optional-parameters)

### Path

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

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

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

[](#regexp)

By default the middleware assumes the value of the header is in `Bearer ` format. You can change this behaviour with `regexp` parameter. For example if you have custom header such as `X-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

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

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

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\JwtAuthentication([
    "secret" => "supersecretkeyyoushouldnotcommittogithub",
    "algorithm" => ["HS256", "HS384"]
]));
```

### Attribute

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

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

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)

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)

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

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

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

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

[](#testing)

You can run tests either manually or automatically on every code change. Automatic tests require [entr](http://entrproject.org/) to work.

```
$ make test
```

```
$ brew install entr
$ make watch
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security-1)

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

License
-------

[](#license)

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

###  Health Score

57

—

FairBetter than 98% of packages

Maintenance28

Infrequent updates — may be unmaintained

Popularity65

Solid adoption and visibility

Community41

Growing community involvement

Maturity81

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 94.8% 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

Every ~84 days

Recently: every ~272 days

Total

42

Last Release

614d ago

Major Versions

1.0.2 → 2.0.22015-12-10

1.0.3 → 2.3.22017-02-27

1.0.4 → 2.3.32017-07-12

2.3.3 → 3.0.0-rc.12017-07-17

2.x-dev → 3.1.02018-08-07

PHP version history (8 changes)0.1.0PHP &gt;=5.3.0

2.0.0PHP &gt;=5.4.0

2.3.1PHP ^5.5 || ^7.0

1.0.3PHP ^5.3

3.0.0-rc.5PHP ^7.1

3.5.0PHP ^7.1|^8.0

3.7.0PHP ^7.2|^8.0

3.8.0PHP ^7.4|^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/3325405a7d8a43bc40dd0e760a4b7f268fba32a7150cf0327f64f13d1661df0b?d=identicon)[tuupola](/maintainers/tuupola)

---

Top Contributors

[![tuupola](https://avatars.githubusercontent.com/u/21913?v=4)](https://github.com/tuupola "tuupola (256 commits)")[![dakujem](https://avatars.githubusercontent.com/u/443067?v=4)](https://github.com/dakujem "dakujem (2 commits)")[![JimTools](https://avatars.githubusercontent.com/u/1222052?v=4)](https://github.com/JimTools "JimTools (2 commits)")[![jhmoon2000](https://avatars.githubusercontent.com/u/30658871?v=4)](https://github.com/jhmoon2000 "jhmoon2000 (1 commits)")[![jv-k](https://avatars.githubusercontent.com/u/5808914?v=4)](https://github.com/jv-k "jv-k (1 commits)")[![klarsson](https://avatars.githubusercontent.com/u/17089222?v=4)](https://github.com/klarsson "klarsson (1 commits)")[![orx0r](https://avatars.githubusercontent.com/u/2333215?v=4)](https://github.com/orx0r "orx0r (1 commits)")[![TiMESPLiNTER](https://avatars.githubusercontent.com/u/598854?v=4)](https://github.com/TiMESPLiNTER "TiMESPLiNTER (1 commits)")[![tuefekci](https://avatars.githubusercontent.com/u/2657626?v=4)](https://github.com/tuefekci "tuefekci (1 commits)")[![BafS](https://avatars.githubusercontent.com/u/588205?v=4)](https://github.com/BafS "BafS (1 commits)")[![xu42](https://avatars.githubusercontent.com/u/12060792?v=4)](https://github.com/xu42 "xu42 (1 commits)")[![bezumkin](https://avatars.githubusercontent.com/u/1257284?v=4)](https://github.com/bezumkin "bezumkin (1 commits)")[![byan](https://avatars.githubusercontent.com/u/383327?v=4)](https://github.com/byan "byan (1 commits)")

---

Tags

jwtmiddlewarepsr-15psr-7token-authenticationpsr-7jwtjsonmiddlewareauthpsr-15

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tuupola-slim-jwt-auth/health.svg)

```
[![Health](https://phpackages.com/badges/tuupola-slim-jwt-auth/health.svg)](https://phpackages.com/packages/tuupola-slim-jwt-auth)
```

###  Alternatives

[jimtools/jwt-auth

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

20142.3k3](/packages/jimtools-jwt-auth)[tuupola/slim-basic-auth

PSR-7 and PSR-15 HTTP Basic Authentication Middleware

4442.0M26](/packages/tuupola-slim-basic-auth)[tuupola/cors-middleware

PSR-7 and PSR-15 CORS middleware

1331.8M24](/packages/tuupola-cors-middleware)[hkarlstrom/openapi-validation-middleware

PSR-7 and PSR-15 OpenAPI Validation Middleware

95198.8k1](/packages/hkarlstrom-openapi-validation-middleware)[jasny/auth

Authentication, authorization and access control for Slim Framework and other PHP micro-frameworks

11816.4k1](/packages/jasny-auth)[mezzio/mezzio-authentication

Authentication middleware for Mezzio and PSR-7 applications

121.6M26](/packages/mezzio-mezzio-authentication)

PHPackages © 2026

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