1
votes

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

1
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
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
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. owasp.org/index.php/… imagining it's roughly the same use-case as other third-party API auth needs, which don't have CSRF worries. - ron pastore

1 Answers

2
votes

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