LoginSignup
23
24

More than 5 years have passed since last update.

apiでdevise認証を叩いてUnauthorizedな時に, redirectなhtmlじゃなくて401のjsonを返したい

Last updated at Posted at 2013-12-16

ref: How To: Redirect to a specific page when the user can not be authenticated · plataformatec/devise Wiki

Devise::FailureAppを継承したCustomFailureを作成, respondメソッドを書き換えてcontent typeがapplication/jsonだったらjson返すようにした. コレ自体がRack appなのか, self.status = 401, という書き換え方で面白い. bodyはとりあえずという感じ.

lib/custom_failure.rb
class CustomFailure < Devise::FailureApp
  def respond
    if http_auth?
      http_auth
    # ここのelsif句を追加
    elsif request.content_type == "application/json"
      self.status = 401
      self.content_type = "application/json"
      self.response_body = {success: false, error: "Unauthorized"}.to_json
    else
      redirect
    end
  end
end

あとlibの読み込み順を先にして,

config/application.rb
config.autoload_paths += %W(#{config.root}/lib)

deviseの設定に加えればok

config/initializers/devise.rb
  config.warden do |manager|
    manager.failure_app = CustomFailure
  end
23
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
24