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

4

5

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.

Issacissachar answered 1/6, 2021 at 20:48 Comment(0)
B
11

in config/session.php

'same_site' => "none",
Bar answered 1/6, 2021 at 21:6 Comment(2)
This is close, but I think not exactly the right answer. This only sets the SameSite setting for session cookies, not any custom cookie I want to set.Issacissachar
Didn't change anything for me for some reason. Still getting the same errorsTerrilyn
I
2

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);
Issacissachar answered 3/6, 2021 at 16:56 Comment(0)
S
2

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');
Sholom answered 20/8, 2021 at 20:49 Comment(0)
Q
1

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

'path' => '/; SameSite=None; secure'
Queue answered 21/12, 2022 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.