Marek Michalik
Marek Michalik

Reputation: 79

Devise and Devise Token Auth

I am trying to make rails web app along with rails API for mobile app. For this purpose I am using Devise along with Devise token auth.

I configured routes as it is written in Devise token auth gem so as I could have routes for regular Devise and Devise auth token.

I have 2 problems:

  1. When I add include DeviseTokenAuth::Concerns::SetUserByToken to application_controller it overwrites Devise authenticate_user! and on web side I am being aunthenticated with token.

Possible solution: I created separet ApiApplicationController from which API controllers inherit.

class ApiApplicationController < ActionController::Base
  include DeviseTokenAuth::Concerns::SetUserByToken
  protect_from_forgery with: :null_session
end
  1. For each POST request which I do in curl to my API I need to add CSRF token.

Possible solution: I could add to both ApplictionController and ApiApplicationController if: Proc.new { |c| c.request.format == 'application/json' } after protect_from_forgery with: :null_session

Upvotes: 2

Views: 2929

Answers (1)

Tan Nguyen
Tan Nguyen

Reputation: 3376

I used to get the same problem to yours, my solution which is currently working:

# application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session, if: ->{request.format.json?}
end

# api_application_controller.rb
class ApiApplicationController < ActionController::Base
  include DeviseTokenAuth::Concerns::SetUserByToken

  before_action :authenticate_user!
end

Upvotes: 2

Related Questions