Invalid CSRF token using Axios
Structuring The Issue
Brief Description
Hello,
i have this sample API
Route.group(() => {
Route.get('/hello', () => ({
greeting: 'This is the real hello world '
}))
Route.post('/hello', async ({request}) => {
console.log(request)
return { greeting: 'Hello from POST!!' }
})
}).prefix('test');
and when i call it from Axios or Postman
the GET works fine.
the POST show:
HttpException
EBADCSRFTOKEN: Invalid CSRF token
its the same problem when using axios from another frontend app.
its about CSRF token !! how can i handle this?
thank you.
Hey @NadhirBoukhenifra! 👋
It seems that you are building an API Only backend. I recommend you to disable the CSRF protection if it's the case.
You can do that by changing the value in the config/shield.js file.
More information about disabling CSRF protection on a REST API.
Closing since talk about that in Gitter and resolved.
For those with the same problem you can get the value of the csrfField and set in your request header like below:
xhr.setRequestHeader('x-csrf-token', document.querySelector('[name="_csrf"]').value);
If you use the Key X-XSRF-TOKEN to set the cookie value of XSRF-TOKEN it will not work, even though it's in the docs...
Yeah, it doesn't work. Seems like the XSRF-TOKEN cookie token is much longer than the value from '{{ csrfToken }}'.
You could add API routes to filtered urls, like this.
in config/shield.js
Modify:
csrf: {
cookieOptions: {
httpOnly: false,
maxAge: 7200,
path: '/',
sameSite: true,
},
enable: true,
filterUris: ['/api/(.*)'],
methods: ['POST', 'PUT', 'DELETE'],
}
Hey @NadhirBoukhenifra! 👋
It seems that you are building an API Only backend. I recommend you to disable the CSRF protection if it's the case.
You can do that by changing the value in the
config/shield.jsfile.More information about disabling CSRF protection on a REST API.
Thank you my config now after disable csrf: { enable: false, methods: ['POST', 'PUT', 'DELETE'], filterUris: [], cookieOptions: { httpOnly: false, sameSite: true, path: '/', maxAge: 7200 } }
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.