PHPackages                             tigerwill90/xsrf-middleware - 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. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. tigerwill90/xsrf-middleware

AbandonedArchivedLibrary[Authentication &amp; Authorization](/categories/authentication)

tigerwill90/xsrf-middleware
===========================

Csrf protection based on double submit pattern, cookie - JWT alternative

1.3.1(8y ago)446MITPHPPHP ^7.1

Since Nov 28Pushed 8y ago2 watchersCompare

[ Source](https://github.com/tigerwill90/xsrf-middleware)[ Packagist](https://packagist.org/packages/tigerwill90/xsrf-middleware)[ Docs](https://github.com/tigerwill90/xsrf-middleware)[ RSS](/packages/tigerwill90-xsrf-middleware/feed)WikiDiscussions master Synced yesterday

READMEChangelogDependencies (13)Versions (8)Used By (0)

[![Latest Stable Version](https://camo.githubusercontent.com/71bbd092ff348b49fa35872cf188aa3342eef236241ebd64973a188600e4b6a2/68747470733a2f2f706f7365722e707567782e6f72672f746967657277696c6c39302f787372662d6d6964646c65776172652f762f737461626c65)](https://packagist.org/packages/tigerwill90/xsrf-middleware)[![Latest Unstable Version](https://camo.githubusercontent.com/23b13df5f171d81bad50d4a372b5d3cd2274fe57e2c63bd18af1ecfcf4313860/68747470733a2f2f706f7365722e707567782e6f72672f746967657277696c6c39302f787372662d6d6964646c65776172652f762f756e737461626c65)](https://packagist.org/packages/tigerwill90/xsrf-middleware)[![License MIT](https://camo.githubusercontent.com/1a2e0606685ce00663bf829868f794fd3fc9c86f8d80cae324734129e0723a58/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d627269676874677265656e2e737667)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/337e2314bb7c8064ae12af430e0cf464eb4f6ce460219c30292830b9d3ebd863/68747470733a2f2f7472617669732d63692e6f72672f746967657277696c6c39302f787372662d6d6964646c65776172652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/tigerwill90/xsrf-middleware)[![codecov](https://camo.githubusercontent.com/9f6299004b2f46f4d665736f0df5273ea6e3d68a8e1fff7778c794b8f84d0beb/68747470733a2f2f636f6465636f762e696f2f67682f746967657277696c6c39302f787372662d6d6964646c65776172652f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/tigerwill90/xsrf-middleware)

PSR-7 &amp; PSR-15 : CSRF Protection alternative for JWT/Branca Authentication token
====================================================================================

[](#psr-7--psr-15--csrf-protection-alternative-for-jwtbranca-authentication-token)

Csrf protection based on double submit pattern, cookie - JWT/Branca alternative.

It is based on [PSR-7 JWT Authentication Middleware](https://github.com/tuupola/slim-jwt-auth) from [Tuupola](https://github.com/tuupola). **This middleware is designed to work with JWT/Branca Authentication method and can be used with any framework using PSR-7 or PSR-15 style middlewares (since v1.1.0). It has been tested with [Slim Framework](https://www.slimframework.com/)**.

This middleware does **not** provide ways to generate Branca/JWT token. However you can find all you needs for generate token with links bellow.

- [Firebase/php-jwt](https://github.com/firebase/php-jwt)
- [Tuupola/branca-php](https://github.com/tuupola/branca-php)
- [Tuupola/base62](https://github.com/tuupola/base62)

The goal is to protect rest api again [Cross-site request forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery)attak, using double submit pattern (stateless).

### How it's work ?

[](#how-its-work-)

Sometimes you want save your Jwt/Branca token in a http only cookie. Since it's not possible to grab it, your payload content is safe. It's particularly true for JWT who have no-encrypted payload. BUT, this protection expose your api to CSRF attack.

When a user authenticate to a site

- generate an anti-csrf `token` with pseudorandom value
- generate `JWT` or `Branca` and set one of payload attribute with the previously `token` generated
- send `JWT` or `Branca` to frontend in a `http-only`, `secure` cookie.
- send the previously `token` generated in the response body

When an authenticated api consumer want access to your api, you need to attach the anti-csrf `token` as

- eventually a cookie with unique name
- a header proprieties
- a request body parameter

For all unsafe operation `[POST | PUT | PATCH | DELETE]` to you api, the middleware inspect both `token` and `JWT` or `Branca` in `http-only` cookie to check if value match and return [401 status](https://httpstatuses.com/401) if not.

### Dependencies

[](#dependencies)

- [dflydev-fig-cookies](https://github.com/dflydev/dflydev-fig-cookies)
- [tuupola/callable-handler](https://github.com/tuupola/callable-handler)
- [tuupola/http-factory](https://github.com/tuupola/http-factory)
- [rybakit/msgpack](https://packagist.org/packages/rybakit/msgpack)
- php-fig standards

### Install

[](#install)

```
composer require tigerwill90/xsrf-middleware

```

### Usage

[](#usage)

Configuration options are passed as an array. There is no mandatory parameter.

```
$app = new Slim\App

$app->add(new Tigerwill90\Middleware\XsrfProtection([]));
```

When a request is made, the middleware inspect both token and cookie to check if value match. If cookie or token is not found, the server will respond with `401 Unauthorized`

### Optional parameters

[](#optional-parameters)

#### Path

[](#path)

The optional `path` parameter allows you to specify which ressources of your api is protected by the double submit pattern. It can be either a string or an array. You do not need to specify each URL.

Default parameter is `/`

```
$app = new Slim\App

$app->add(new Tigerwill90\Middleware\XsrfProtection([
    "path" => "/api" /* or ["/api", "/admin"]*/
]));
```

In this example, everything starting with `/api` will be protected.

#### Passthrough

[](#passthrough)

The optional `passthrough` parameter allows you to specify an exceptions to `path` parameter. It can be either a string or an array.

Default parameter is `null`

```
$app = new Slim\App

$app->add(new Tigerwill90\Middleware\XsrfProtection([
    "path" => ["/api", "/admin"],
    "passthrough" => "/api/orders"
]));
```

In this example, everything starting with `/api` and `/admin` will be protected, **except** `/api/orders`

#### AntiCsrf

[](#anticsrf)

The optional `anticsrf` parameter allow you to specify the name of your anti-csrf cookie, header or parameter.

Default parameter is `xCsrf`

```
$app = new Slim\App

$app->add(new Tigerwill90\Middleware\XsrfProtection([
    "path" => ["/api", "/admin"],
    "anticsrf" => "xCsrf"
]));
```

In this example, if the cookie, header or request parameter "xCsrf" exist, the middleware will compare his value with the specified JWT/Branca token `claim` value.

#### Token

[](#token)

According to [PSR-7 JWT Authentication Middleware](https://github.com/tuupola/slim-jwt-auth) documentation, when the token is decoded successfully and authentication succees, the contents of decoded token is saved as attribute to the `$request`. The optional `token` parameter allows you to specify the attribute name of JWT/Branca token that the middleware needs to find in `$request`.

Default parameter is `token`

```
$app = new Slim\App

$app->add(new Tigerwill90\Middleware\XsrfProtection([
"path" => ["/api", "/admin"],
"token" => "jwt"
]));
```

#### Payload

[](#payload)

**Alternatively** you can pass the contents of decoded token in the optional `payload` parameter.

Default value is `null`

```
$app = new Slim\App

$app->add(new Tigerwill90\Middleware\XsrfProtection([
  "path" => ["/api", "/admin"],
  "payload" => $container["decoded"]
]));
```

#### Claim

[](#claim)

Beauty of JWT/Branca is that you can pass extra data in the token such roles, rights, etc... Therby, we can compare a specified claims with `httponly` cookie.

```
[
   "uid" => 1,
   "iat" => "1428819941",
   "exp" => "1744352741",
   "aud" => "www.example.com",
   "roles" => [1,0,1,1,1],
   "xsrf" => "thepseudorandomvaluegeneratedforbothcookieandtoken"
]
```

The optional `claim` parameter allows you to specify the name of the `claim` that the middleware need to find in decoded JWT/Branca token.

Default value is `csrf`

```
$app = new Slim\App

$app->add(new Tigerwill90\Middleware\XsrfProtection([
  "path" => ["/api", "/admin"],
  "claim" => "xsrf"
]));
```

According to this example, when a request is send to your api, you should have in the header a `httponly` cookie and an `authorization` token who have both `thepseudorandomvaluegeneratedforbothcookieandtoken`setted as value.

#### Logger

[](#logger)

The optional `logger` parameter allows you to pass a PSR-3 compatible logger to deal with debugging.

```
use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Formatter\LineFormatter;

$app = new Slim\App

$logger = new Logger("slim");
$formatter = new LineFormatter(
    "[%datetime%] [%level_name%]: %message% %context%\n",
    null,
    true,
    true
);

$rotating = new RotatingFileHandler(__DIR__ . "/logs/xsrf.log", 0, Logger::DEBUG);
$rotating->setFormatter($formatter);
$logger->pushHandler($rotating);

$app->add(new Tigerwill90\Middleware\XsrfProtection([
  "path" => ["/api", "/admin"],
  "claim" => "xsrf",
  "logger" => $logger
]));
```

In this example we pass an instance of [Logger](https://github.com/projek-xyz/slim-monolog) `$logger` to the middleware.

```
[2017-12-06 01:14:05] [WARNING]: Payload not found in parameter
[2017-12-06 01:14:05] [DEBUG]: Token and cookie don't match, access denied !

```

#### Error

[](#error)

Error is called when access is denied. It receives last error message in arguments.

```
$app = new Slim\App

$app->add(new Tigerwill90\Middleware\XsrfProtection([
  "path" => ["/api", "/admin"],
  "claim" => "xsrf",
  "error" => function ($response, $arguments) {
       $data["message"] = $arguments["message];
       return $response
                ->withHeader("Content-Type", "application/json")
                ->write(json_encode($data));
  }
]));
```

#### MessagePack

[](#messagepack)

The optional `msgpack` parameter allows you to use the [MessagePack](https://msgpack.org/) serialization format.

Default value is `false`

```
$app = new Slim\App

$app->add(new Tigerwill90\Middleware\XsrfProtection([
   "path" => ["/api", "/admin"],
   "payload" => $container["decoded"]
   "msgpack" => true
]));
```

### Implementation with JWT/Branca Authentication Middleware

[](#implementation-with-jwtbranca-authentication-middleware)

Branca/JWT Authentication Middleware need to run before Xsrf Middleware protection.

```
$container = $app->getContainer();

$container["XsrfProtection"] = function($c) {
    function new \Tigerwill90\Middleware\XsrfProtection([
        "path" => "/api",
        "passthrough" => ["/api/users/signin", "/api/users/token"],
        "anticsrf" => "xCsrf",
        "token" => "jwt",
        "claim" => "xsrf"
    ]);
};

 $container["JwtAuthentication"] = function($c) {
    return new \Slim\Middleware\JwtAuthentication([
        "secure" => true,
        "path" => "/api",
        "passthrough" => ["/api/users/signin", "/api/users/token"],
        "attribute" => "jwt",
        "secret" => getenv("JWT_SECRET")
    ]);
 };

 $app->add("XsrfProtection");
 $app->add("JwtAuthentication");
```

### Testing

[](#testing)

```
phpunit

```

### License

[](#license)

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

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community4

Small or concentrated contributor base

Maturity63

Established project with proven stability

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 ~13 days

Recently: every ~1 days

Total

7

Last Release

3005d ago

PHP version history (2 changes)1.0.2PHP ^5.5 || ^7.0

1.1.0PHP ^7.1

### Community

Maintainers

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

---

Tags

jwtmiddlewareauthcookiecsrfxsrfbranca

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tigerwill90-xsrf-middleware/health.svg)

```
[![Health](https://phpackages.com/badges/tigerwill90-xsrf-middleware/health.svg)](https://phpackages.com/packages/tigerwill90-xsrf-middleware)
```

###  Alternatives

[tuupola/slim-basic-auth

PSR-7 and PSR-15 HTTP Basic Authentication Middleware

4442.0M26](/packages/tuupola-slim-basic-auth)[cakephp/authentication

Authentication plugin for CakePHP

1153.6M67](/packages/cakephp-authentication)[jimtools/jwt-auth

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

20142.3k3](/packages/jimtools-jwt-auth)[yiisoft/yii-middleware

Yii Middleware

21151.3k1](/packages/yiisoft-yii-middleware)[selective/samesite-cookie

Secure your site with SameSite cookies

10144.0k](/packages/selective-samesite-cookie)

PHPackages © 2026

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