When sending an ajax request to api it does not verify the token, disabling verifyCsrfToken middleware in Ap\Http\kernel of api works. I strictly followed all the rules according to the docs in laravel 5.5, It works perfectly when redirecting internally in main project but breaks when sending post request to API. Any suggestions ? Thanks in advance.
You might want to read the docs: Routing. It states:
"...These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group."
I tried by placing route in api.php but same error. I also tried response headers but it did not work.
If I exclude it, of course it works but it would mean that i need to exclude all the routes and I don't think it is a good idea. Any suggestions ? , Thanks in advance.
I checked laravel log and all I figured out is that it throws 419 status because it is a TokenMismatchException, and after research I figured it out that I was on correct path and I need to allow Cross-Origin Resource Sharing(CORS) from API, I returned response with Headers as mentioned in DOCS but not working, any idea ?? I even tried laravel cors at "https://github.com/barryvdh/laravel-cors". Any Idea what is causing this ????
I solved the problem by placing "header('Access-Control-Allow-Origin : *')" in bootstrap/app.php, but that is little bit odd thing. Is it valid if on production ?
That change can get overridden when you update laravel. You should never alter code in /vendor.
It would be better to create your own middleware and use that instead of the default. You can set which middleware runs in /app/Http/kernel.php. Just replace \App\Http\Middleware\VerifyCsrfToken::class, with your own class in the web middleware group.
@pjn I can't believe this is a solution, this is just a workaround. What you just did is disabling csrf checking for post requests...
The method you are changing is isReading(). This method will return true after your change on post requests and will never fire the the TokenMismatchException anymore.
public function handle($request, Closure $next)
{
if (
$this->isReading($request) ||
$this->runningUnitTests() ||
$this->inExceptArray($request) ||
$this->tokensMatch($request)
) {
return $this->addCookieToResponse($request, $next($request));
}
throw new TokenMismatchException;
}
So for everyone else that is here for a solution: Do NOT change the isReading() method but actually solve the problem you have