Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP SameSite session problem, session doesn't work

I hope anybody can give me some ideas to my problem. I am trying to apply SameSite cookie to make session work but it seems it doesn't work. The visited site html:

<iframe src="https://www.example.com/test/iframe.php"></iframe>

Iframe source site:

    <?php
    header('Set-Cookie: cross-site-cookie=PHPSESSID; SameSite=None; Secure');
    session_start();
    if(!isset($_SESSION['test'])){
        echo 1;
        $_SESSION['test'] = 'ee2';
    }else{
        echo $_SESSION['test'];
    }

If I visit the website, I still receive A cookie associated with a cross-site resource at https://www.example.com/ was set without the SameSite attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with SameSite=None and Secure. message in browser console and session is not saved.

Strange thing is that the cookie has been actually set: enter image description here

Am I missing something? Why do I get this message in console if cross-site-cookie is set and what could be reasons for session to not work? I am using php 7.1.33. If I open iframe directly, it works and it also works properly if I open the site with browser where I haven't enabled the SameSite by default cookies flag for testing.

like image 480
JohnyFree Avatar asked Feb 10 '20 19:02

JohnyFree


3 Answers

Set session & cookies param php: https://www.php.net/manual/en/function.session-set-cookie-params.php Browser: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

<?php
session_set_cookie_params(["SameSite" => "Strict"]); //none, lax, strict
session_set_cookie_params(["Secure" => "true"]); //false, true
session_set_cookie_params(["HttpOnly" => "true"]); //false, true
session_start(); //everything before this

OR php.ini:

[Session]
session.cookie_samesite = "Strict"
session.cookie_secure = 1
session.cookie_httponly = 1
like image 83
Franco Michel Almeida Caixeta Avatar answered Oct 08 '22 06:10

Franco Michel Almeida Caixeta


I resolved it by editing .htaccess

<ifmodule mod_headers.c>
Header always edit Set-Cookie ^(.*)$ $1;SameSite=None;Secure
</ifmodule> 
like image 13
Behiry Avatar answered Oct 08 '22 07:10

Behiry


I temporary resolved my problem using htaccess:

Header edit Set-Cookie ^(.*)$ $1;SameSite=None;Secure
like image 5
JohnyFree Avatar answered Oct 08 '22 05:10

JohnyFree