PHPackages                             binarcode/laravel-stateless-session - 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. [Security](/categories/security)
4. /
5. binarcode/laravel-stateless-session

ActiveLibrary[Security](/categories/security)

binarcode/laravel-stateless-session
===================================

This package allow you to keep the session through request/response header. No cookie needed.

1.1.0(5y ago)321.3k2MITPHPPHP ^7.2

Since Apr 5Pushed 5y ago2 watchersCompare

[ Source](https://github.com/BinarCode/laravel-stateless-session)[ Packagist](https://packagist.org/packages/binarcode/laravel-stateless-session)[ Docs](https://github.com/binarcode/laravel-stateless-session)[ RSS](/packages/binarcode-laravel-stateless-session/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)Dependencies (3)Versions (6)Used By (0)

CSRF verification and session persistent through request/response headers.
==========================================================================

[](#csrf-verification-and-session-persistent-through-requestresponse-headers)

This is a lightweight package which allow you to manage a session in a stateless communication (REST/API) when the API domain and main web application domain are different.

E.g.

- API hosted under: `api.foo.com`
- WEB hosted under: `tenant1.com`, `tenant2.com` etc.

In that case you cannot set cookie for different main domains

[See why you cannot set cookie under different domain.](https://blog.webf.zone/ultimate-guide-to-http-cookies-2aa3e083dbae)

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require binarcode/laravel-stateless-session
```

Usage
-----

[](#usage)

1. Trigger session, make a GET request to: `/api/csrf-header`. This will return a header with the session key and an optional header with CSRF token `XSRF-TOKEN`. The header name could be configured in: `stateless.header`
2. Use this header session key/value for every request you want to take care of the session.
3. If you want to benefit of the CSRF protection of your requests, you should add the follow middlewares to your routes:

```
use Binarcode\LaravelStatelessSession\Http\Middleware\StatelessStartSession;
use Binarcode\LaravelStatelessSession\Http\Middleware\StatelessVerifyCsrfToken;

->middleware([
    StatelessStartSession::class,
    StatelessVerifyCsrfToken::class,
]);
```

You can create a middleware group in your Http\\Kernel with these 2 routes as:

```
protected $middlewareGroups = [
// ...
    'stateless.csrf' => [
        StatelessStartSession::class,
        StatelessVerifyCsrfToken::class,
    ],
// ...
]
```

Now the server will return 419 (Page expired code).

Unless you send back a request header named: `X-CSRF-TOKEN` with the value received by the first GET request in the `XSRF-TOKEN` header.

Done.

- At this point you have CSRF protection.
- And you can play with `SessionManager` and use the `session()` helper to store/get information (e.g. flash sessions).

Config
------

[](#config)

The lifetime and other options could be set as before in the `session` file.

The `VerifyHeaderCsrfToken` and `StartStatelessSession` middlewares will inject into headers the session key.

The session key name could be configured in the:

```
stateless.header => env('STATELESS_HEADER', 'X-STATELESS-HEADER')
```

Danger: The key name separators should use `-` not `_` [according with this](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers).

You can customize the middleware for the `csrf-header` route. In some cases you may need some custom cors middleware for example:

```
stateless.middleware => [
    \Barryvdh\Cors\HandleCors::class,
]
```

### Real use case

[](#real-use-case)

Let's say you want to allow visitors to submit a newsletter form. You want also to protect your API with CSRF.

You can setup a GoogleRecaptcha for that, but that's so annoying.

Solution:

Vue newsletter page:

```
// Newsletter.vue
{
    async created() {
        const response = await axios.get(`${host}/api/csrf-header`);
        this.csrfToken =  response.headers['XSRF-TOKEN'];
        this.sessionKey =  response.headers['LARAVEL-SESSION'];
    },
    methods: {

        async subscribe() {
            await axios.post(`${host}/api/newsletter`, {email: 'foo@bar.com'}, {
                headers: {
                    'LARAVEL-SESSION': this.sessionKey,
                    'X-CSRF-TOKEN': this.csrfToken
                }
            });
        }

    }
}
```

`api.php`

```
Route::post('api/subscribe', function (Request $request) {

    // at this point the CSRF token is verified

    Subscribers::createFromEmail($request->get('email'));

    return response('', 201)->json();

})->middleware([
    StartStatelessSession::class,
    VerifyHeaderCsrfToken::class,
]);
```

### Testing

[](#testing)

```
composer test
```

### Changelog

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

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

[](#contributing)

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

### Security

[](#security)

Since the Session Key and X-CSRF-TOKEN could be read by the JavaScript code, that means it's less secure than a usual http-only Cookie. But since we have different domains for the API and WEB, we don't have a way to setup a cookie. You can think of this as of the Bearer token. The security impact is exactly the same.

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

Credits
-------

[](#credits)

- [Eduard Lupacescu](https://github.com/binarcode)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity25

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~13 days

Total

5

Last Release

2173d ago

Major Versions

0.1.1 → 1.0.02020-04-05

### Community

Maintainers

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

---

Top Contributors

[![binaryk](https://avatars.githubusercontent.com/u/6833714?v=4)](https://github.com/binaryk "binaryk (13 commits)")

---

Tags

csrflaravelphpsecuritysessionbinarcodelaravel-stateless-session

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/binarcode-laravel-stateless-session/health.svg)

```
[![Health](https://phpackages.com/badges/binarcode-laravel-stateless-session/health.svg)](https://phpackages.com/packages/binarcode-laravel-stateless-session)
```

###  Alternatives

[illuminate/encryption

The Illuminate Encryption package.

9229.7M280](/packages/illuminate-encryption)[tzsk/otp

A secure, database-free One-Time Password (OTP) generator and verifier for PHP and Laravel.

241641.4k1](/packages/tzsk-otp)[genealabs/laravel-governor

Managing policy and control in Laravel.

201262.8k](/packages/genealabs-laravel-governor)[dgtlss/warden

A Laravel package that proactively monitors your dependencies for security vulnerabilities by running automated composer audits and sending notifications via webhooks and email

8745.6k](/packages/dgtlss-warden)[ercsctt/laravel-file-encryption

Secure file encryption and decryption for Laravel applications

642.6k](/packages/ercsctt-laravel-file-encryption)[laragear/poke

Keep your forms alive, avoid TokenMismatchException by gently poking your Laravel app

2211.5k](/packages/laragear-poke)

PHPackages © 2026

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