我创建了一个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
-方法是罪魁祸首,它发送的是纯文本(而不是你的问题所建议的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
从Rails 5开始, 验证或请求_http_token。 方法允许第二个参数带有自定义信息,所以你可以直接做。
authenticate_or_request_with_http_token('realm', json_error) do |token, options|
check_token token
end