gonzalo-bulnes / simple_token_authentication

Simple (and safe*) token authentication for Rails apps or API with Devise.
GNU General Public License v3.0
1.51k stars 240 forks source link

Is that gem work with API? #348

Open Uysim opened 5 years ago

Uysim commented 5 years ago

I have my controller

 class BaseController < ActionController::API
    acts_as_token_authentication_handler_for User, fallback: :exception
end 

I expect to it to render json error. But it redirect me to /user/sign_in page of devise. And what kind of exception you raise?

exocode commented 5 years ago

not sure if I am right, but I think you have to override the Devise controller action which causes the redirect. Please someone correct me if I am wrong

andreydro commented 4 years ago

Having the same issue

andreydro commented 4 years ago

I found solution. You need to override devise failture_app. That is how you can make different behavior for website and api

# lib/custom_failure.rb
class CustomFailure < Devise::FailureApp
  def respond
    if request.env['REQUEST_PATH'].start_with?('/api')
      http_auth
    else
      redirect_to new_user_session_path
    end
  end
end

# config/initializers/devise.rb
config.warden do |manager|
  manager.failure_app = CustomFailure
end

Do not forger to load lib folder in application.rb

config.autoload_paths << Rails.root.join('lib')
drihu commented 4 years ago

I think maybe you need a fallback (just don't set it) and send a http header Accept: application/json