2020/09/02

Chrome SameSite Cookie Policy Causes Problem :: Logout When Direct To External Website Then Back Own Site



Recently I am working on a function, when user submits the form then it will direct to the external website, and we will give a return URL via the form, let the external website can lead the users back to our website after finish their manipulation.


Then I encountered a problem, the users will be automatically logged out when the external websites redirect to our website.


After debugging, I discovered that the session ID is different from the origin session ID when users direct back to our website, and it only occurs in Chrome, Safari, IE, Edge, firefox works fine.


Why? It turns out that Chrome enforces set SameSite = LAX cookies, so we need to set the SameSite = 'None', that Secure will be available on a third-party website.


So, Let's start to edit the SamSite attribute,
First, you may want to know "Is that the logout reason really was caused by SameSite ?"
That's fine, we can test it w/o modifying code.
Enter chrome://flags/ in the URL bar,
search "Samesite" then turn it as disabled,
press the button "Relaunch" to relaunch the setting on the bottom right corner.





To test the users will log out or not.
If it works, then the problem definitely is SameSite.



However, that's impossible to ask every user to change the setting,
that's all right we have a couple of methods to solve the problem,



1. Set the header


If your PHP version < 7.3.0

header('Set-Cookie: cross-site-cookie=name; SameSite=None; Secure');

or

header('Set-Cookie: cookie2=name; SameSite=None; Secure', false);



If your PHP version >= 7.3.0

setcookie('cookie2', 'name', ['samesite' => 'None', 'secure' => true]);

or

setcookie('cross-site-cookie', 'name', ['samesite' => 'None', 'secure' => true]);

Use the name of 'sessionID' to replace 'name' 
If you setting success you will see the context which was wrapped by red line.






2. Set the .htaccess

Header always edit Set-Cookie ^(.*)$ "$1;HttpOnly;Secure;SameSite=None"



3. Set the httpd.conf


Header always edit Set-Cookie ^(.*)$ "$1;HttpOnly;Secure;SameSite=None"

Remember to reload the apache after setting up