22

デバイスのauthenticate_userを使用します!コントローラのメソッド。これは、リクエストで提供されたauth_tokenが正しい場合は正常に機能しますが、認証が失敗した場合は、次のようになります。

curl -XGET 'http://localhost:3000/my_obj?auth_token=wrongtoken'

<html><body>You are being <a href="http://localhost:3000/users/sign_in">redirected</a>.</body></html>

私はrablを使用しているので、次のようなものを作成するための最良の方法は何ですか

{'error' : 'authentication error'}

htmlリダイレクトの代わりに返されましたか?

4

2 に答える 2

43

:format =>:json応答でフィルターを回避し、current_userパスがない場合は、独自のフィルターを実行してJSON応答をレンダリングします。

class MyController < ApplicationController
  before_filter :authenticate_user!, :unless => { request.format == :json }
  before_filter :user_needed, :if => { request.format == :json }

  def user_needed
    unless current_user
      render :json => {'error' => 'authentication error'}, :status => 401
    end
  end
end

もう1つの方法は、独自のFailureAppを定義することです(https://github.com/plataformatec/devise/blob/master/lib/devise/failure_app.rb

class MyFailureApp < Devise::FailureApp
  def respond
    if request.format == :json
      json_failure
    else
      super
    end
  end

  def json_failure
    self.status = 401
    self.content_type = 'application/json'
    self.response_body = "{'error' : 'authentication error'}"
  end
end

Devise構成ファイルに以下を追加します。

config.warden do |manager| 
  manager.failure_app = MyFailureApp 
end 
于 2012-04-06T10:15:01.053 に答える
37

Deviseの新しいバージョン(私は2.2.0を使用しています)navigational_formatsでは、Devise構成ファイルのオプションを使用できdevise.rbます。

# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
config.navigational_formats = ["*/*", :html]

:jsonそのリストになく、リクエストがで終わる限り、リクエストは.json希望どおりに動作します。

于 2013-06-11T17:30:37.630 に答える