Search code examples
phplaravelautomated-testscsrf-protection

How do I enable VerifyCsrfToken for some tests?


Laravel by default disables VerifyCsrfToken middleware if running tests. As a result I didn't notice that api routes need csrf token to succeed. Is there a way to enable it back for some tests? Like

function withVerifyCsrfTokenMiddleware()
{
    $this->app...   // here we're passing something to the app
}

And make amendments in VerifyCsrfToken's handle method. In a custom one. The one, that overrides the method from the framework. But that's just my idea. Any better ones?


Solution

  • Okay, here's what I did:

    app/Http/Middleware/VerifyCsrfToken.php:

    function handle($request, Closure $next)
    {
        $dontSkipCsrfVerificationWhenRunningTests
            = $this->app->bound('dontSkipCsrfVerificationWhenRunningTests')
                && $this->app->make('dontSkipCsrfVerificationWhenRunningTests');
        if (
            $this->isReading($request) ||
            ! $dontSkipCsrfVerificationWhenRunningTests && $this->runningUnitTests() ||
            $this->shouldPassThrough($request) ||
            $this->tokensMatch($request)
        ) {
            return $this->addCookieToResponse($request, $next($request));
        }
    
        throw new TokenMismatchException;
    }
    

    tests/TestCase.php:

    function withVerifyCsrfTokenMiddleware()
    {
        $this->app->instance('dontSkipCsrfVerificationWhenRunningTests', TRUE);
    }