Rails - How to add CSRF Protection to forms created in javascript?
I have a form inside a Vue component in a Rails 6 app.
To my surprise, it was sufficient to include a hidden input with the name authenticity_token
within the Vue template and on page load, Rails filled out the value with a CSRF protection token.
E.g.
<template>
<div id="app">
<form
action="/submit"
method="post"
@submit.prevent="onSubmit"
>
<input
type="hidden"
name="authenticity_token"
value=""
>
<!-- rest of form -->
</form>
</div>
</template>
Which gets rendered as:
<div id="app">
<form action="/submit" method="post">
<input type="hidden" name="authenticity_token" value="zl9PJiE...">
...
</form>
</div>
If you have <%= csrf_meta_tag %>
in your layout somewhere and that is accessible to you from the js, then you can access it using $('meta[name="csrf-token"]')
See http://eunikorn.blogspot.com/2011/07/working-with-backbonejs-in-harmony-with.html for an idea on how to hack in csrf support into each backbone request
Best way I solved this, inside the form:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
Update:
It looks like the form_authenticity_token
is private for controllers in the newer rails versions.
If that's the case for you, what I suggest is: declare a variable in a controller like:
@form_token = form_authenticity_token
and use it in the view you are looking for.