Question

I use Backbone on frontend, and Ruby on Rails on backend. I have devise gem, for my authentication. A couple of days before, frontend team, finished their part of work, and now I need to bind this all together. So I try to send data with json trough backbone (standard way) with request Started POST "/users/sign_in.json", and I get an error Completed 401 Unauthorized in 180ms even if I put protect_from_forgery except: :create in my custom sessions controller. Like this:

class UserSessions::SessionsController < Devise::SessionsController

    protect_from_forgery except: :create
    ......
end

How to omit this, or where i must generate my <%= csrf_meta_tags %> so I can use this approach which I found on web:

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

Backbone.sync = (function(original) {
  return function(method, model, options) {
    options.beforeSend = function(xhr) {
      xhr.setRequestHeader('X-CSRF-Token', App.csrfToken);
    };
    original(method, model, options);
  };
})(Backbone.sync);

I can't move this back to standard rails assets pipeline, because the frontend was written separately from my backend, which is depended on require.js.

Was it helpful?

Solution

You could put the csrf_meta_tags into a partial, then make an ajax request from public/index to a method that returns that partial.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top