authenticate_or_request_with_http_token返回html而不是json。

问题描述 投票:17回答:2

我创建了一个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
ruby-on-rails json rails-api
2个回答
32
投票

通过将 ActionController::HttpAuthentication::Token::ControllerMethods 你包括几种方法,其中包括 request_http_token_authentication 的包装物,它只是一个 Token.authentication_request. 那 #authentication_request-方法是罪魁祸首,它发送的是纯文本(而不是你的问题所建议的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

诀窍是覆盖 request_http_token_authentication 在你 ApplicationController 召唤 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

0
投票

从Rails 5开始, 验证或请求_http_token。 方法允许第二个参数带有自定义信息,所以你可以直接做。

  authenticate_or_request_with_http_token('realm', json_error) do |token, options|
    check_token token
  end
© www.soinside.com 2019 - 2024. All rights reserved.