John Davidson

php - vue js spa and laravel sanctum: cannot set crsf-cookie

0 comments
Message:


CONTEXT AND GOAL


I have my laravel backend running on backend.domain


I have a vuejs spa trying to logging in from 'external.app.domain'


I need that vuejs spa can login, obatain A NEW token for the user, to, then, use for subsequent calls.


WHAT I DID


I am following this: https://laravel.com/docs/9.x/sanctum#csrf-protection


The call to sanctum/csrf-cookie works, but I got this from chrome



Axios in vue app is using


withCredentials: true,

Backend cors.php file has


'supports_credentials' => true,

Backend sanctum.php file has external.app.domain in the stateful array


THE MAIN PROBLEM


The problem is that calling /login to obtain a token I got this


CSRF token mismatch.

Simple question


What else must I do !?



My Answer:
In addition to the steps you have already taken, you may need to ensure that your Vue.js application is sending the CSRF token with the login request. Here are a few steps you can take to troubleshoot the issue:

1. Make sure that your Vue.js application is sending the CSRF token with the login request. You can do this by including the CSRF token in the headers of the Axios request:

javascript
axios.post('/login', {
email: 'example@example.com',
password: 'password'
}, {
headers: {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
}
})


2. Check if the CSRF token is being set correctly in your Laravel application. You can do this by inspecting the response headers of the /sanctum/csrf-cookie request to see if the X-CSRF-TOKEN cookie is being set.

3. Make sure that the CSRF token is being included in the headers of subsequent requests after obtaining the token. This is important for Laravel Sanctum to validate the CSRF token on each request.

By following these steps, you should be able to resolve the CSRF token mismatch issue and successfully obtain a token for the user in your Vue.js SPA.

Rate this post

4 of 5 based on 6741 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us