psr7-sessions / storageless
Storageless PSR-7 Session support
Requires
- php: ~8.4.0 || ~8.5.0
- ext-sodium: *
- dflydev/fig-cookies: ^3.2.0
- lcobucci/jwt: ^5.6.1
- psr/clock: ^1.0.0
- psr/http-message: ^1.1 || ^2.0
- psr/http-server-handler: ^1.0.2
- psr/http-server-middleware: ^1.0.2
Requires (Dev)
- doctrine/coding-standard: ^14.0.0
- infection/infection: ^0.35.6
- laminas/laminas-diactoros: ^3.9.0
- laminas/laminas-httphandlerrunner: ^2.14.0
- lcobucci/clock: ^3.6.0
- phpstan/phpstan: ^2.3.1
- phpstan/phpstan-phpunit: ^2.1.1
- phpunit/phpunit: ^13.4.1
Suggests
None
Provides
None
Conflicts
None
Replaces
- ocramius/psr7-session: 10.3.0
- 10.4.x-dev
- 10.3.x-dev
- 10.3.0
- 10.2.x-dev
- 10.2.1
- 10.2.0
- 10.1.x-dev
- 10.1.0
- 10.0.x-dev
- 10.0.0
- 9.4.x-dev
- 9.3.x-dev
- 9.3.0
- 9.2.x-dev
- 9.2.0
- 9.1.x-dev
- 9.1.0
- 9.0.x-dev
- 9.0.1
- 9.0.0
- 8.18.x-dev
- 8.17.x-dev
- 8.17.0
- 8.16.x-dev
- 8.16.0
- 8.15.x-dev
- 8.15.0
- 8.14.x-dev
- 8.14.0
- 8.13.x-dev
- 8.13.0
- 8.12.x-dev
- 8.12.0
- 8.11.x-dev
- 8.11.0
- 8.10.x-dev
- 8.10.0
- 8.9.x-dev
- 8.9.0
- 8.8.x-dev
- 8.8.0
- 8.7.x-dev
- 8.7.0
- 8.6.x-dev
- 8.6.0
- 8.5.x-dev
- 8.5.0
- 8.4.x-dev
- 8.4.0
- 8.3.x-dev
- 8.3.0
- 8.2.x-dev
- 8.2.0
- 8.1.x-dev
- 8.1.0
- 8.0.x-dev
- 8.0.0
- 7.4.x-dev
- 7.3.x-dev
- 7.3.0
- 7.2.x-dev
- 7.2.0
- 7.1.x-dev
- 7.1.0
- 7.0.x-dev
- 7.0.0
- 6.0.x-dev
- 6.0.0
- 5.1.0
- 5.0.x-dev
- 5.0.0
- 4.0.x-dev
- 4.0.0
- 3.0.x-dev
- 3.0.1
- 3.0.0
- 2.0.x-dev
- 2.0.0
- 1.0.x-dev
- 1.0.2
- 1.0.1
- 1.0.0
- dev-feature-session-cache-limiter
- dev-fix-session-cookie-in-shared-caches
- dev-9.3.x-merge-up-into-10.0.x_GWlJBIsA
- dev-master
This package is auto-updated.
Last update: 2026-10-17 05:49:18 UTC
README
PSR7Session is a PSR-7 and PSR-15 compatible middleware that enables session without I/O usage in PSR-7 based applications.
Proudly brought to you by ocramius, malukenho and lcobucci.
Installation
composer require psr7-sessions/storageless
Usage
You can use the PSR7Sessions\Storageless\Http\SessionMiddleware in any
PSR-15
compatible middleware.
In a mezzio/mezzio
application, this would look like following:
use Lcobucci\JWT\Configuration as JwtConfig; use Lcobucci\JWT\Signer; use Lcobucci\JWT\Signer\Key\InMemory; use PSR7Sessions\Storageless\Http\SessionMiddleware; use PSR7Sessions\Storageless\Http\Configuration as StoragelessConfig; $app = new \Mezzio\Application(/* ... */); $app->pipe(new SessionMiddleware( StoragelessConfig::fromJwtConfiguration( JwtConfig::forSymmetricSigner( new Signer\Hmac\Sha256(), InMemory::base64Encoded((string) getenv('SESSION_SIGNING_KEY')), // see below on how to generate it ) ) ));
After this, you can access the session data inside any middleware that
has access to the Psr\Http\Message\ServerRequestInterface attributes:
$app->get('/get', function (ServerRequestInterface $request, ResponseInterface $response) : ResponseInterface { $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE); assert($session instanceof \PSR7Sessions\Storageless\Session\SessionInterface); $session->set('counter', $session->get('counter', 0) + 1); $response ->getBody() ->write('Counter Value: ' . $session->get('counter')); return $response; });
You can do this also in asynchronous contexts and long-running processes, since no super-globals nor I/O are involved.
Anyone knowing the signing key can forge any session, so the key must be
kept secret, outside of your codebase (for example in an environment variable),
and generated using a cryptographically secure pseudo-random number generator
(CSPRNG). Never use a key found in documentation or examples.
For the Sha256 signer above, you can generate a key with:
php -r 'echo base64_encode(random_bytes(32)), PHP_EOL;'
An empty key is rejected, so a missing environment variable makes the configuration fail instead of silently using a weak key.
Note that you can also use asymmetric keys; please refer to
lcobucci/jwt documentation:
- The
Configurationobject: https://lcobucci-jwt.readthedocs.io/en/stable/configuration/ - Supported algorithms: https://lcobucci-jwt.readthedocs.io/en/stable/supported-algorithms/
Session Hijacking mitigation
To mitigate the risks associated to cookie stealing and thus
session hijacking,
you can bind the user session to its IP ($_SERVER['REMOTE_ADDR']) and
User-Agent ($_SERVER['HTTP_USER_AGENT']) by enabling client fingerprinting:
use PSR7Sessions\Storageless\Http\SessionMiddleware; use PSR7Sessions\Storageless\Http\Configuration as StoragelessConfig; use PSR7Sessions\Storageless\Http\ClientFingerprint\Configuration as FingerprintConfig; $app = new \Mezzio\Application(/* ... */); $app->pipe(new SessionMiddleware( StoragelessConfig::fromJwtConfiguration(/* ... */) ->withClientFingerprintConfiguration( FingerprintConfig::forIpAndUserAgent() ) ));
When a request lacks any of the fingerprint sources (for example, it has no
User-Agent header), its session cookie is ignored and no session cookie is
sent back to it: such a client is served an empty session that is never persisted.
If no session ever persists, check that your server provides all the configured
sources, such as $_SERVER['REMOTE_ADDR'].
If your PHP service is behind a reverse proxy of yours, you may need to retrieve the client IP from a different source of truth.
In such cases you can extract the information you need by writing a custom
\PSR7Sessions\Storageless\Http\ClientFingerprint\Source implementation.
Headers such as X-Real-IP or X-Forwarded-For are sent by the client as well:
only trust them when the request comes from your own reverse proxy, and make sure
that the proxy overwrites them instead of appending to the values sent by the client.
Otherwise, an attacker that stole a session cookie can simply send the header with
the victim's IP:
use Psr\Http\Message\ServerRequestInterface; use PSR7Sessions\Storageless\Http\SessionMiddleware; use PSR7Sessions\Storageless\Http\Configuration as StoragelessConfig; use PSR7Sessions\Storageless\Http\ClientFingerprint\Configuration as FingerprintConfig; use PSR7Sessions\Storageless\Http\ClientFingerprint\Source; use PSR7Sessions\Storageless\Http\ClientFingerprint\SourceMissing; use PSR7Sessions\Storageless\Http\ClientFingerprint\UserAgent; final class ClientIpBehindTrustedProxy implements Source { /** @param list<non-empty-string> $trustedProxies IPs of your own reverse proxies */ public function __construct(private readonly array $trustedProxies) { } public function extractFrom(ServerRequestInterface $request): string { $remoteAddr = $request->getServerParams()['REMOTE_ADDR'] ?? ''; if (! is_string($remoteAddr) || $remoteAddr === '') { throw SourceMissing::for('REMOTE_ADDR'); } if (! in_array($remoteAddr, $this->trustedProxies, true)) { // not coming from your proxy: the peer itself is the client return $remoteAddr; } $clientIp = $request->getHeaderLine('X-Real-IP'); if ($clientIp === '') { throw SourceMissing::for('X-Real-IP'); } return $clientIp; } } $app = new \Mezzio\Application(/* ... */); $app->pipe(new SessionMiddleware( StoragelessConfig::fromJwtConfiguration(/* ... */) ->withClientFingerprintConfiguration( FingerprintConfig::forSources( new ClientIpBehindTrustedProxy(['10.0.0.10']), new UserAgent(), ) ) ));
Examples
Simply browse to the examples directory in your console, then run
SESSION_SIGNING_KEY="$(php -r 'echo base64_encode(random_bytes(32));')" php -S localhost:9999 index.php
Then try accessing http://localhost:9999: you should see a counter
that increases at every page refresh
WHY?
In most PHP+HTTP related projects, ext/session serves its purpose and
allows us to store server-side information by associating a certain
identifier to a visiting user-agent.
What is the problem with ext/session?
This is all fair and nice, except for:
- relying on the
$_SESSIONsuperglobal - relying on the shutdown handlers in order to "commit" sessions to the storage
- having a huge limitation of number of active users (due to storage)
- having a lot of I/O due to storage
- having serialized data cross different processes (PHP serializes and
de-serializes
$_SESSIONfor you, and there are security implications) - having to use a centralized storage for setups that scale horizontally
- having to use sticky sessions (with a "smart" load-balancer) when the storage is not centralized
- not designed to be used for multiple dispatch cycles
What does this project do?
This project tries to implement storage-less sessions and to mitigate the issues listed above.
Assumptions
- your sessions are fairly small and contain only few identifiers and
some CSRF tokens. Small means less than
512bytes, when JSON encoded (see the limitations documentation) - data in your session is
JsonSerializableor equivalent - data in your session is freely readable by the client: sessions are signed, not encrypted, so they must never contain secrets (see the limitations documentation)
How does it work?
Session data is directly stored inside a session cookie as a JWT token.
This approach is not new, and is commonly used with Bearer tokens in
HTTP/REST/OAuth APIs.
In order to guarantee that the session data is not modified, that the client can trust the information and that the expiration date is mutually agreed between server and client, a JWT token is used to transmit the information.
The JWT token is always signed to ensure that the user-agent is never able to manipulate the session. Both symmetric and asymmetric keys are supported for signing/verifying tokens.
Advantages
- no storage required
- no sticky sessions required (any server having a copy of the private or public keys can generate sessions or consume them)
- can transmit cleartext information to the client, allowing it to share some information with the server (a standard example is about sharing the "username" or "user-id" in a given session)
- not affected by PHP serialization RCE attacks
- not limited to PHP process scope: can have many sessions per process
- no reliance on global state
- when in a multi-server setup, you may allow read-only access to servers that only have access to public keys, while writes are limited to servers that have access to private keys
- can be used over multiple dispatch cycles
Configuration options
Please refer to the configuration documentation.
Known limitations
Please refer to the limitations documentation.
Contributing
Please refer to the contributing notes.
License
This project is made public under the MIT LICENSE.