odan / session

A middleware oriented session handler for PHP and Slim 4+
https://odan.github.io/session/
MIT License
58 stars 11 forks source link

How to set cookie and csrf #6

Closed terabytesoftw closed 5 years ago

terabytesoftw commented 5 years ago

I am interested in working with slim4, I have put the session middleware to work, how can I correctly implement cookies and csrf,

Thks,

odan commented 5 years ago

Hi @terabytesoftw

how can I correctly implement cookies and csrf,

Cookies are handled by this session library. You can use these methods to manage cookies:

// Set session runtime configuration
// All supported keys: http://php.net/manual/en/session.configuration.php
$session->setOptions($options);

// Get session runtime configuration
$session->getOptions();

// Set cookie parameters
$session->setCookieParams(4200, '/', '', false, false);

// Get cookie parameters
$session->getCookieParams();

CSRF is not part of this library. But you could take a look at this here:

Here is an example how to integrate odan/session and odan/csrf in combination with league/container:

And here you can find an older Slim 3 example:

I hope it helps you.

terabytesoftw commented 5 years ago

I am working with Yii3 and Slim4, the middleware works correctly, but the session does not generate the cookie.

SessionInterface::class => function (\Psr\Container\ContainerInterface $container) {
    $settings  = [
        'name' => 'webapp',
        'cache_expire' => 0,
        'cookie_httponly' => true,
        'cookie_secure' => true,
        'cache_limiter' => '',
        // garbage collection
        'gc_probability' => 1,
        'gc_divisor' => 1,
        'gc_maxlifetime' => 30 * 24 * 60 * 60,
    ];
    $session = new \Odan\Session\PhpSession();
    $session->setOptions($settings);
    return $session;
},

SessionMiddleware::class => function (\Psr\Container\ContainerInterface $container) {
    return new SessionMiddleware($container->get(SessionInterface::class));
},

CsrfMiddleware::class => function (ContainerInterface $container) {
    $session = $container->get(\Odan\Session\SessionInterface::class);

    // The CSRF middleware requires a valid session id
    if (!$session->isStarted()) {
        $session->start();
    }
    return new CsrfMiddleware(new Psr17Factory(), $session->getId());
},

Thks,

terabytesoftw commented 5 years ago

Solved,

Thks,