jeudi 23 juillet 2015

Can't verify CSRF token authenticity even when X-CSRF-Token is in header - Rails API with Ember.js

I know there are tons of questions of this topic, but I haven't found what's causing my problem.

Problem

I get the message on my rails server Can't verify CSRF token authenticity even when I can see on Chrome the header is present. (as shown in picture)

X-CSRF-Token

My setup

  • Rails 4.2 as backend RESTful API
  • Ember.js 1.11.3 for frontend
  • devise
  • Ember-Simple-Auth.

I followed these instructions of how to setup ember-simple-auth-devise which uses authentication via token. I did everything the same with one exception, instead of putting the next code inside ApplicationController I defined an ApiController class in an effort to separate my API logic from the rest of the site.

class ApiController < ActionController::Base

  protect_from_forgery with: :null_session

  before_action :authenticate_user_from_token!

  # I had to comment this line out in order to 
  # make the authentication work
  # before_filter :authenticate_user!

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(
      :username, :first_name, :last_name, :email, :password, :password_confirmation
    ) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(
      :username, :first_name, :last_name, :email, :password, :current_password
    ) }
  end

  private

  def authenticate_user_from_token!
    authenticate_with_http_token do |token, options|
      user_email = options[:email].presence
      user = user_email && User.find_by_email(user_email)

      if user && Devise.secure_compare(user.authentication_token, token)
        sign_in user, store: false
      end
    end
  end
end

Please note that I had to comment before_filter :authenticate_user! out to make the authentication work. With that line I only get 401 unauthorized requests.

I hope someone can give me some insight of:

-Why Am I getting the Can't verify CSRF token authenticity even when the X-CSRF-Token is in header

-Why would be important/necesary to keep the line I commented from the example instructions?

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire