ember-cli addon to keep track of your Rails CSRF-token.
npm install rails-csrf --save- In
app.jsadd load initializers
loadInitializers(App, 'rails-csrf');- Add a before model to your application route so your token is fetched automatically.
export default Ember.Route.extend({
beforeModel: function() {
return this.csrf.fetchToken();
}
});By default rails-csrf does a get request to /api/csrf, if you
want to customize the end-point use setCsrfUrl on app.js
import { setCsrfUrl } from 'rails-csrf/config';
setCsrfUrl('/api/your/own/endpoint');
...
loadInitializers(App, 'rails-csrf');The following controller will return the required payload to get everything working.
class Api::CsrfController < ApplicationController
def index
render json: { request_forgery_protection_token => form_authenticity_token }.to_json
end
endAdd route
namespace :api do
get :csrf, to: 'csrf#index'
end
Be sure to mock out the call to the csrf server endpoint. Otherwise your tests will fail with
"error while processing route: [route]"
messages in the browser console. For example:
server = new Pretender(function() {
this.get('/csrf', function(request) {
return [200, {"Content-Type": "application/json"},
JSON.stringify({
"authenticity_token": "token"
})
];
});
rails-csrf is MIT Licensed.