1

I really frustrating with this error, I have datatable with ajax post request, but the error CSRF token mismatch rarely appear. this my jquery ajax post setup

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

ajax:{
    "url": "trip/jsondata",
    "dataType": "json",
    "type": "POST",
    "data" : function ( d ){
        d.nState= $('#viewoption').val(),
        d.nYear  = $('#viewyear').val();
    }
},

I courious why my post request return CSRF token mismatch, so I've modified the Illuminate\Foundation\Http\Middleware\VerifyCsrfToken file to return the token values like below.

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);
            }
        });
    }

    $error='getTokenFromRequest :'.$this->getTokenFromRequest($request).' | X-CSRF-TOKEN :'.$request->header('X-CSRF-TOKEN').' | Session :'.$request->session()->token();
    throw new TokenMismatchException('CSRF token mismatch. err: '.$error);
}

I Try to return 3 variables (getTokenFromRequest, X-CSRF-TOKEN, and the Session token). And the result is:

message: "CSRF token mismatch. err: getTokenFromRequest :w0nxu5OPWZHFrBFqMtLsL3IWJ1vCg0VAGbCDt4c3 | X-CSRF-TOKEN :w0nxu5OPWZHFrBFqMtLsL3IWJ1vCg0VAGbCDt4c3 | Session :CiMUsbN9BumKIElvrOzJX8TnCA8UeuAAaLzbfZTO"

You can see there is a different between X-CSRF-TOKEN with Session Token, I don't know why?

Then I try to check in the storage\framework\sessions folder, there are two files. enter image description here

The first file filled like this a:7:{s:6:"_token";s:40:"w0nxu5OPWZHFrBFqMtLsL3IWJ1vCg0VAGbCDt4c3";

The second file filled like this a:2:{s:6:"_token";s:40:"CiMUsbN9BumKIElvrOzJX8TnCA8UeuAAaLzbfZTO";

Anyone can help what's happen in my application? is it normal have 2 sessions at the same time with a different token?

4

0 回答 0