core icon indicating copy to clipboard operation
core copied to clipboard

Invalid CSRF token using Axios

Open NadhirBoukhenifra opened this issue 8 years ago • 7 comments

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

01

its the same problem when using axios from another frontend app. its about CSRF token !! how can i handle this? thank you.

NadhirBoukhenifra avatar Jan 27 '18 16:01 NadhirBoukhenifra

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.

RomainLanz avatar Jan 27 '18 17:01 RomainLanz

Closing since talk about that in Gitter and resolved.

RomainLanz avatar Jan 27 '18 17:01 RomainLanz

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...

lucasctd avatar Dec 28 '18 18:12 lucasctd

Yeah, it doesn't work. Seems like the XSRF-TOKEN cookie token is much longer than the value from '{{ csrfToken }}'.

s-appdeveloper avatar Feb 02 '19 10:02 s-appdeveloper

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'],
  }

belal-mazlom avatar Nov 26 '19 14:11 belal-mazlom

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.

Thank you my config now after disable csrf: { enable: false, methods: ['POST', 'PUT', 'DELETE'], filterUris: [], cookieOptions: { httpOnly: false, sameSite: true, path: '/', maxAge: 7200 } }

YvesBoah avatar Dec 02 '19 19:12 YvesBoah

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.

lock[bot] avatar Mar 10 '20 20:03 lock[bot]