2

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

Marek Michalik
  • 79
  • 3
  • 10
  • I would suggest you to make the authentification by yourself and drop deviseauthtoken, I used it for a mobile app and it's a mess, really hard to dig in when you've problem and it's consume so much ressources. Make the authentification with devise and secure it by yourself with a api token – Thounder Sep 01 '16 at 21:12
  • Thanks for advice, but even if I would do it myself I still don't know if it is secure to disable CSRF token authentication for json requests. – Marek Michalik Sep 01 '16 at 21:16
  • auth library aside, i believe it's ok to disable CSRF token for JSON requests against an API, assuming the API has token auth or other auth implemented safely/correctly, like using header. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Protecting_REST_Services:_Use_of_Custom_Request_Headers imagining it's roughly the same use-case as other third-party API auth needs, which don't have CSRF worries. – ron pastore Sep 01 '16 at 21:46

1 Answers1

2

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
Tan Nguyen
  • 3,281
  • 1
  • 18
  • 18