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

另一种更简洁的方法是定义自己的 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

在您的设计配置文件中添加:

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

在较新版本的 Devise(我使用的是 2.2.0)中,您可以使用navigational_formatsDevise 配置文件中的选项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 回答