Passing X-CSRF-Token (Ruby on Rails)
See original GitHub issueIn 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:
- Created 7 years ago
- Reactions:7
- Comments:14 (4 by maintainers)
Top 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 >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@peric You need to set
header
props:'X-Requested-With': 'XMLHttpRequest'
, andcredentials: 'same-origin'
.Updated: to make rails accept JSON post, add the following code to header:
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: