[Solved] api endpoint not doing CSRF token validation on Sanctum - CSRF Token Mismatch

Article Ab Siddik

Problem:

Nowadays, we working on a SPA(Single page application), we used Laravel and React to develop this application. We implemented Sanctum to authentication. But when we implemented Sanctum we face an error. The error is "CSRF Token Mismatch".


Solution:

Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. In this article I will not discuss what is sanctum or its requirements. I will try to explain here, we face some problems when we send request from Axios after installing sanctum and "CSRF token mismatch" is one of them.

Basically, we don't get any problem when we send GET request. But when we send a POST request we get this error "CSRF Token Mismatch". Actually, we need to authenticate our SPA or our SPA's "login" page should first make a request to the "/sanctum/csrf-cookie" endpoint to initialize CSRF protection for the application.

axios.get('/sanctum/csrf-cookie').then(response => {
    // Login...
});

This request, our laravel app will set an XSRF-TOKEN cookie containing the current CSRF token. This token should then be passed in an X-XSRF-TOKEN header on subsequent requests, which some HTTP client libraries like Axios and the Angular HttpClient will do automatically for us. If does not set the value, we will need to manually set the X-XSRF-TOKEN header to match the value of the XSRF-TOKEN cookie that is set by this route. After CSRF protection has been initialized, we should make a POST request to our app.

Thank you for reading the article. If you face any problems, please comment below.