繁体   English   中英

authentication_or_request_with_http_token 返回 html 而不是 json

[英]authenticate_or_request_with_http_token returning html instead of json

我已经创建了一个 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

通过包含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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM