【问题标题】:authenticate_or_request_with_http_token returning html instead of jsonauthenticate_or_request_with_http_token 返回 html 而不是 json
【发布时间】:2013-07-18 00:04:14
【问题描述】:

我创建了一个 rails-api 应用程序并继续使用令牌身份验证来保护它。

我设置了一个before_filter,它正在调用一个使用authenticate_or_request_with_http_token 的方法。一切正常,但是当身份验证不正确时,我会收到一个 html 响应。

如何定义响应的格式?

before_filter :restrict_access

private

def restrict_access
  authenticate_or_request_with_http_token do |token, options|
    check_token token
  end
end

def check_token(token)
  Session.exists?(access_token: token)
end

【问题讨论】:

  • 您能否展示您的一些代码以便人们实际提供帮助。
  • @GoGoGarrett 更新了我的问题。

标签: ruby-on-rails json rails-api


【解决方案1】:

通过包含ActionController::HttpAuthentication::Token::ControllerMethods,您可以包含多种方法,其中包括request_http_token_authentication,它只是Token.authentication_request 的包装。 #authentication_request-method 是罪魁祸首,它发送纯文本(不是您的问题所暗示的 HTML),如下所示:

def authentication_request(controller, realm)
  controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
  controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
end

诀窍是将ApplicationController 中的request_http_token_authentication 重写为 调用Token.authentication_request,而是设置正确的状态和标题,然后改为呈现JSON。将此添加到您的ApplicationController

protected
def request_http_token_authentication(realm = "Application")
  self.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
  render :json => {:error => "HTTP Token: Access denied."}, :status => :unauthorized
end

【讨论】:

  • 目前,您必须将此函数定义为request_http_token_authentication(realm = 'Application', message = nil)
  • “当前”是指Rails edge,@DiegoCouto?
  • 没错@berkes! Take a look。感谢您指出这一点,顺便说一句。 :-)
【解决方案2】:

从 Rails 5 开始,authenticate_or_request_with_http_token 方法允许带有自定义消息的第二个参数,因此您可以这样做:

  authenticate_or_request_with_http_token('realm', json_error) do |token, options|
    check_token token
  end

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 2017-03-28
    • 2019-03-31
    相关资源
    最近更新 更多