question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Passing X-CSRF-Token (Ruby on Rails)

See original GitHub issue

In Ruby on Rails, you need to pass X-CSRF-Token in POST request header in order to properly handle the form. jquery-ujs basically handles that by default, but if you are not using it or you want to send requests with some other libraries (like fetch), you need to pass this header by your own.

In jQuery, this can be handle (and this works) like:

var token = $('meta[name="csrf-token"]').attr('content');

$.ajax({
    url: '/somecustomurl',
    type: 'post',
    beforeSend: function (xhr) {
        xhr.setRequestHeader('X-CSRF-Token', token)
    },
    data: {},
    contentType: false,
    processData: false
});

With fetch, I’ve tried:

fetch('/somecustomurl', {
  method: 'POST',
  headers: {
    'X-CSRF-Token': token
  },
  body: JSON.stringify({})
})

And this example never works - controller will always raise a InvalidAuthenticityToken exception.

Any ideas how can this be solved with fetch?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:7
  • Comments:14 (4 by maintainers)

github_iconTop GitHub Comments

124reactions
origamihcommented, Nov 8, 2016

@peric You need to set header props: 'X-Requested-With': 'XMLHttpRequest', and credentials: 'same-origin'.

fetch(url, { 
      method: 'POST',
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-Token': token
      },
      body: ,
      credentials: 'same-origin'
    })

Updated: to make rails accept JSON post, add the following code to header:

'Content-Type': 'application/json',
        'Accept': 'application/json'
12reactions
mislavcommented, Apr 11, 2017

How will we be able to use fetch now, to send each forms own token?

The way we do this in GitHub.com is to generate an actual <form> element on the server, via Rails’ form_tag helper. Each form generated that way also includes the per-form token. Then, if we need to post that form using JavaScript, we simply use FormData:

fetch(form.action, {
  method: 'POST',
  body: new FormData(form)
})
Read more comments on GitHub >

github_iconTop Results From Across the Web

A Deep Dive into CSRF Protection in Rails | by Alex Taylor
Rails protects against this kind of attack by generating unique tokens and validating their authenticity with each submission.
Read more >
Rails CSRF Protection Guide: Examples and How to Enable
Rails CSRF Token ​​ The server generates these tokens, links them to the user session, and stores them in the database. This token...
Read more >
Securing Rails Applications - Ruby on Rails Guides
The above method can be placed in the ApplicationController and will be called when a CSRF token is not present or is incorrect...
Read more >
How to pass the CSRF token between rails applications
CSRF tokens are "session dependent" this means the user must share a session with the application he is communicating with. This means a...
Read more >
Each form gets its own CSRF token in Rails 5 - BigBinary Blog
Nested form can get around CSRF protection offered by Rails 4 · Rails 5 fixes the issue by generating a custom token for...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found