It sounds like you're encountering an issue where the CSRF token is not being consistently set or recognized across your subdomains. Here's a solution that might help you resolve the issue:
- Ensure that your
SESSION_DOMAINis correctly set to the base domain with a leading dot to allow for subdomain access. For example, if your domain isexample.com, your.envfile should have:
SESSION_DOMAIN=.example.com
- For
SANCTUM_STATEFUL_DOMAINS, you should list all the domains and subdomains that should be treated as "stateful" for SPA authentication. Make sure you separate them with commas and no spaces:
SANCTUM_STATEFUL_DOMAINS=staging.example.com,example.com
- Clear your config cache to make sure your changes take effect. You can do this by running the following command in your terminal:
php artisan config:clear
-
Also, clear your cookies in the browser for both the main domain and the subdomain. This is important because the browser might be holding onto old cookies that are causing the conflict.
-
Ensure that your middleware is set up correctly. If you're using Laravel Sanctum, make sure you have the
EnsureFrontendRequestsAreStatefulmiddleware included in yourapimiddleware group inapp/Http/Kernel.php:
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
// ...
],
- Verify that your front-end application is configured to send the
XSRF-TOKENcookie in the header of every request. If you're using Axios, you can set up default headers like this:
axios.defaults.withCredentials = true;
axios.defaults.headers.common['X-XSRF-TOKEN'] = getCookie('XSRF-TOKEN');
function getCookie(name) {
let cookie = {};
document.cookie.split(';').forEach(function(el) {
let [k,v] = el.split('=');
cookie[k.trim()] = v;
})
return cookie[name];
}
- If you're using multiple subdomains and notice that the CSRF token is still not being set correctly, you might need to adjust the
config/session.phpconfiguration to ensure thedomainis set to your base domain:
'domain' => env('SESSION_DOMAIN', null),
By following these steps, you should be able to resolve the issue of having two XSRF tokens and ensure that the correct token is used for your staging and production environments. If the problem persists, you may need to debug further by checking the network requests and responses to see exactly when and where the additional token is being set.