'Is it possible to rename the XSRF-TOKEN cookie that Laravel is creating?
My Laravel application is hosted on the same domain name (one application on only one subdomain, the other one on multiple subdomains) as another web application that use a XSRF-TOKEN cookie. The two cookies are conflicting. Is there any way to rename Laravel's cookie to something like XSRF-TOKEN_Second? I am using Laravel version 6. I apologize if the question was asked before, couldn't find an answer. Thanks!
My solution
The problem was, in .env APP_NAME had same value on both projects. Rename one and it will change the name of the session and no more conflicts.
Solution 1:[1]
You can set your own token by modifying the response:
$response->headers->setCookie(
new Cookie(
'NEW-XSRF-TOKEN-NAME',
$request->session()->token(),
$this->availableAt(60 * $config['lifetime']),
$config['path'],
$config['domain'],
$config['secure'],
false,
false,
$config['same_site'] ?? null
)
);
And you should update your middleware for checking the new token. X-XSRF-TOKEN, as per their docs, is just there for developer convenience. However, I still urge you not to write your own csrf logic.
Solution 2:[2]
I was facing the same problem with 2 laravel apps on the same domain that communicate with each other, eg:
https://example.com/store/
https://example.com/gateway/
The CSRF tokens were competing with each other. It turns out that the easiest way to fix it was to set the session cookie path in config/session.php as follows:
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
// fixes conflicts between store and gateway CSRF tokens
'path' => '/store/',
and the same on the gateway:
'path' => '/gateway/',
Update: It's actually better not to hardcode the session cookie path, so the APP_URL can be changed later without breaking. Here's the code update:
'path' => parse_url(env('APP_URL'), PHP_URL_PATH),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jerven Clark |
| Solution 2 |
