Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

localpathcomp's avatar

Production wildcard csrf cookie interferes with staging subdomains

Using sanctum for auth and having to support subdomains means I need a wildcard session domain. This causes issues with CSRF mismatch if a user visits production then visits staging for instance. If we could specify the session domains like how we can with sanctum that would work great I would think as well.

# production
SESSION_DOMAIN=.example.com
# staging
SESSION_DOMAIN=.staging.example.com

Is there a work around within laravel to ignore cookies from certain domains that could be placed in effect for staging?

Not using the wildcard subdomain is not an option when using sanctum unfortunately or the fix would be simple.

Finally, you should ensure your application's session cookie domain configuration supports any subdomain of your root domain. You may accomplish this by prefixing the domain with a leading . within your application's config/session.php configuration file:

0 likes
1 reply
LaryAI's avatar
Level 58

One possible solution is to modify the VerifyCsrfToken middleware to exclude certain subdomains from CSRF protection. This can be done by adding a condition to the shouldPassThrough method that checks the current subdomain and excludes it if it matches a list of allowed subdomains.

Here's an example implementation:

// app/Http/Middleware/VerifyCsrfToken.php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    protected $exceptSubdomains = [
        'staging',
    ];

    protected function shouldPassThrough($request)
    {
        foreach ($this->exceptSubdomains as $subdomain) {
            if ($request->subdomain() === $subdomain) {
                return true;
            }
        }

        return parent::shouldPassThrough($request);
    }
}

In this example, we've added a property $exceptSubdomains that contains a list of subdomains that should be excluded from CSRF protection. We then override the shouldPassThrough method to check if the current subdomain matches any of the allowed subdomains, and if so, return true to skip CSRF protection.

Note that this implementation assumes that you have a custom subdomain method on your Request object that returns the current subdomain. You may need to implement this method yourself depending on your application's routing setup.

Also note that excluding certain subdomains from CSRF protection may introduce security risks, so be sure to carefully consider the implications before implementing this solution.

Please or to participate in this conversation.