通过包括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
诀窍是request_http_token_authentication
在您不调用但设置正确的状态和标头然后呈现 JSON 的情况ApplicationController
下覆盖。将此添加到您的:Token.authentication_request
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