PSR-7 JWT cookie handler
Pikkuleipa is a cookie manager for PSR-7 compliant applications, utilizing JSON Web Tokens for security and allowing the handling of multiple independent cookies.
Install via composer:
$ composer require dasprid/pikkuleipa
Getting started (for Expressive)
Create a file named
pikkuleipa.global.php or similar in your autoloading config directory:
<?php return (new DASPRiD\Pikkuleipa\ConfigProvider())->__invoke();
This will introduce a few factories, namely you can retrieve the following objects through that:
For Pikkuleipa to function, it needs a few configuration variables. Copy the file
doc/example-config.php and adjust the
values as needed.
The token manager should usually not be of interest to you. The important part is the cookie manager, which you can either use through the container, if you are using PSR/Container, or by other means. It concretely gives you three actions you can do, which are setting cookies, getting cookies and expiring cookies.
Setting a cookie is really easy. First you either get an existing cookie from the cookie manager or you create a new one. Then you set that cookie on a PSR-7 response and return the modified response to the user.
setCookie method takes two additional parameters beside the response and the cookie. The first one is whether the
cookie should expire at the end of the browser session, which defaults to false. The second one defines whether the
setCookie call should override a previous
expireCookie call, which defaults to true.
<?php use DASPRiD\Pikkuleipa\Cookie; use DASPRiD\Pikkuleipa\CookieManagerInterface; $cookieManager = $container->get(CookieManagerInterface::class); $cookie = new Cookie('foo'); $cookie->set('bar', 'baz'); $newResponse = $cookieManager->setCookie($response, $cookie);
Getting cookies is also quite simple. When retrieving a cookie, the cookie- and the token manager will verify that the cookie exists and its contents are legit. If something fails, a new empty cookie instance is returned.
<?php use DASPRiD\Pikkuleipa\CookieManagerInterface; $cookieManager = $container->get(CookieManagerInterface::class); $cookie = $cookieManager->getCookie($serverRequest, 'foo'); echo $cookie->get('bar'); // Outputs: bar
Expiring cookies is just as simple as setting a cookie. You can either expire a cookie by its instance or by name:
<?php use DASPRiD\Pikkuleipa\CookieManagerInterface; $cookieManager = $container->get(CookieManagerInterface::class); $cookie = $cookieManager->getCookie($serverRequest, 'foo'); $newResponse = $cookieManager->expireCookie($cookie); // Or: $newResponse = $cookieManager->expireCookieByName('foo');
Pikkuleipa is the Finnish word for "cookie" or "biscuit", nothing fancy here!