Search code examples
phplaravellaravel-5csrf

How to exclude CSRF token for specific domain?


I am hoping to disable CSRF verification tokens for a specific domain. For example, my EC2 instances. This is so that I can run live-cross browser testing on my EC2 instance without any issues.

I've found a lot of info on updating the VerifyCsrfToken in the middleware directory for specific routes within the app, but nothing on how to check the host or domain. I can use /* in my protected URIs.

class VerifyCsrfToken extends BaseVerifier
{
    /**
    * The URIs that should be excluded from CSRF verification.
    *
    * @var array
    */

    protected $except = [
        '/*'
    ];
}

However, for obvious reasons, I would prefer not to use this approach.

I am using a standard Laravel 5.3 setup, so have usual middleware files that come with this framework in use.

Any help would be appreciated!


Solution

  • You could check the host used to make a request in the CSRF middleware and act accordingly. Add the following in your VerifyCsrfToken class:

    public function handle($request, Closure $next)
    {
        if ($request->getHost() == 'some.host.without.csrf.protection') {
            // skip CSRF check
            return $next($request);
        }
    
        return parent::handle($request, $next);
    }