Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename PHP session cookie with __Secure-/__Host- prefix

I'm trying to rename my PHP session cookie from PHPSESSID to __Secure-PHPSESSID as per https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#Examples.

Since PHP does not offer this mechanism, I am doing it through Apache server configuration:

RequestHeader edit Cookie ^__Secure-PHPSESSID(.*)$ PHPSESSID$1
Header edit Set-Cookie ^PHPSESSID(.*)$ __Secure-PHPSESSID$1
Header edit Set-Cookie ^(.*)(?<!SameSite=Strict)(?<!SameSite=Lax)$ "$1;SameSite=Lax"

This works correctly in Firefox, Edge, and Safari, but not Chrome. On Chrome, I can see that the cookie is set with the correct name and flags but I cannot log in to my site.

Upon login, the output of var_dump($_SESSION['internal']['user_name']) is NULL on Chrome but shows the correct username on Firefox and other browsers. I can also see that the session ID is being regenerated every time I try to log in and the value is set in the __Secure-PHPSESSID cookie.

I tried removing the SameSite flag (line 3 above) and it still does not work.

Any ideas?

like image 440
rink.attendant.6 Avatar asked Dec 18 '22 02:12

rink.attendant.6


2 Answers

PHP does indeed offer this mechanism. You can change it in php.ini. Just set this and restart the site:

session.name = __SECURE-PHPSESSID

To confirm it's right, restart your browser to clear previous session cookies.

As for Chrome not letting you log in, this page may give you some clues (see "Option Secure" and "Prefixes" sections): https://www.mon-code.net/post/108/Secure-cookie-of-you-web-application-with-PHP-or-Symfony

They are not well known, but supported by all browsers except those of Microsoft. With prefixes, it's possible to force the browser to not accept a cookie if it's misconfigured. There are two prefixes "__Secure-" and "__Host-". __Secure- forces the developer to add the secure flag to his cookie, otherwise it will be ignored by the browser.

setcookie('__Secure-user_id', 10, 0, '/', 'orion.dev', true);

__Host- is more restrictive, cookie must have the secure flag but also path to root and blank domain.

setcookie('__Host-user_id', 10, 0, '/', '', true);

like image 121
Stephen R Avatar answered Dec 28 '22 06:12

Stephen R


I'm not familiar with Cookie Prefixes but PHP should support it out of the box:

<?php

session_name('__Secure-PHPSESSID');
session_start();

Set-Cookie

like image 43
Álvaro González Avatar answered Dec 28 '22 07:12

Álvaro González