The CSRF token mismatch error typically occurs when the Laravel backend expects a valid CSRF token for a POST request, but the token is either missing or incorrect. Since you're using Laravel Sanctum, it's important to ensure that the SPA (Single Page Application) is properly configured to handle CSRF protection.
Here's a checklist to help you troubleshoot and resolve the CSRF token mismatch issue:
-
Ensure CSRF Cookie Request is Made: Before making any POST requests, you should request the CSRF cookie from the
/sanctum/csrf-cookieendpoint. It looks like you're already doing this in your Angular component, which is good. -
Check SESSION_DOMAIN Configuration: The
SESSION_DOMAINshould match the domain from which your Angular application is making requests. If your Angular app is served from a different domain or subdomain, you need to specify it here. For local development, setting it to.localhostmight help to include all subdomains. -
Verify SANCTUM_STATEFUL_DOMAINS: Make sure that the
SANCTUM_STATEFUL_DOMAINSincludes the domain and port from which your Angular application is served. If your Angular app is running onlocalhost:4200, thenlocalhost:4200should be included in the list. -
CORS Configuration: Your CORS configuration seems to be permissive, which is fine for local development. However, ensure that the
supports_credentialsis set totrueto allow cookies to be sent with cross-origin requests. -
Middleware Configuration: The
EnsureFrontendRequestsAreStatefulmiddleware should be included in yourapimiddleware group, which it is according to yourkernel.php. This middleware will attempt to authenticate using session state, which is necessary for CSRF protection to work. -
Frontend Axios Configuration: Ensure that withCredentials is set to true for all requests, not just the default configuration. This is necessary for cookies to be included in the request.
-
Clear Cookies and Cache: Sometimes, old cookies can cause issues. Clear your cookies and cache in the browser and try again.
-
Check Network Requests: Use your browser's developer tools to inspect the network requests. Make sure that the CSRF token cookie (
XSRF-TOKEN) is being sent with the login request. -
Check Laravel Logs: If the issue persists, check the Laravel logs for any additional information that might help you debug the problem.
If after going through this checklist the issue still persists, you might want to try the following code snippet in your Angular component to ensure that the CSRF token is being set correctly:
axios.get('/sanctum/csrf-cookie').then(response => {
// After this request, the XSRF-TOKEN cookie should be set
axios.post('/login', {
email: '[email protected]',
password: 'password'
}, {
headers: {
'X-XSRF-TOKEN': getCookie('XSRF-TOKEN') // Get the CSRF token from the cookie
}
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response)
});
});
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
This function getCookie is used to retrieve the CSRF token from the cookies and include it in the headers of the POST request. However, this should not be necessary if withCredentials is set to true and the backend is configured correctly, as Axios should handle this automatically.