simple_token_authentication icon indicating copy to clipboard operation
simple_token_authentication copied to clipboard

Is that gem work with API?

Open Uysim opened this issue 5 years ago • 4 comments

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?

Uysim avatar Aug 16 '19 12:08 Uysim

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

exocode avatar Oct 22 '19 09:10 exocode

Having the same issue

andreydro avatar Jan 25 '20 13:01 andreydro

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')

andreydro avatar Jan 25 '20 14:01 andreydro

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

drihu avatar Jun 05 '20 14:06 drihu