tobyreed's avatar

Set expiry of CSRF token in PHPUnit test

Hello,

We have an issue in our PROD where users/we will get a 419 status code (CSRF token expired) from what I understand. I am trying to debug this and make a test from it too. But I am wondering is there a way to expire the CSRF token on a test, I have googled it but cannot find anything of actual value that could help :/

0 likes
3 replies
Nakov's avatar

@tobyreed

The problem is that the testing environment excludes token checks, this is the handle method within the VerifyCsrfToken middleware:

public function handle($request, Closure $next)
    {
        if (
            $this->isReading($request) ||
            $this->runningUnitTests() ||
            $this->inExceptArray($request) ||
            $this->tokensMatch($request)
        ) {
            return tap($next($request), function ($response) use ($request) {
                if ($this->shouldAddXsrfTokenCookie()) {
                    $this->addCookieToResponse($request, $response);
                }
            });
        }

        throw new TokenMismatchException('CSRF token mismatch.');
    }

So in order to test it, you can try setting the APP_ENV to something other than testing for that particular test.

1 like
tobyreed's avatar

Interesting, I did not know this, thank you I will give that a go! But my issue is how exactly would I test this, is there a way to forcefully expire the csrf token? if so then how?

Thank you

Nakov's avatar

As I said :) the token is not even checked in a testing environment, so there is no way to make expire something that is not even checked. And there is the last line in my previous reply that gives you an idea on how you might try to test it.

Please or to participate in this conversation.