Magmatic
Magmatic

Reputation: 1949

How do a make a cookie in Laravel and specify the SameSite attribute (Lax, None, Strict)?

I'm currently setting a cookie like this (in middleware):

cookie()->queue("loginToken", $loginToken, 60*24*365*10);

How do I specify SameSite = None?

I'm using Laravel 8.

Upvotes: 5

Views: 21977

Answers (4)

crwh05
crwh05

Reputation: 105

You could also set it in the path of config/session.php but it's a bit hacky

'path' => '/; SameSite=None; secure'

Upvotes: 1

rsanchez
rsanchez

Reputation: 14657

The cookie function declaration is:

function cookie($name = null, $value = null, $minutes = 0, $path = null, $domain = null, $secure = null, $httpOnly = true, $raw = false, $sameSite = null)

And queue just forwards the parameters, so you can do:

cookie()->queue("loginToken", $loginToken, 60*24*365*10, null, null, null, true, false, 'None');

Upvotes: 2

Magmatic
Magmatic

Reputation: 1949

This is what I did. Remember, this is in the handle function of the middleware.

    $response = $next($request);

    // https://symfony.com/doc/current/components/http_foundation.html#setting-cookies
    // https://github.com/symfony/symfony/blob/5.3/src/Symfony/Component/HttpFoundation/Cookie.php
    $cookie = \Symfony\Component\HttpFoundation\Cookie::create("loginToken")
        ->withValue($loginToken)
        ->withExpires(strtotime("+12 months"))
        ->withSecure(true)
        ->withHttpOnly(true)
        ->withSameSite("strict")
        ;

    $response->headers->setCookie($cookie);

Upvotes: 2

Dri372
Dri372

Reputation: 1321

in config/session.php

'same_site' => "none",

Upvotes: 11

Related Questions