[英]authenticate_or_request_with_http_token returning html instead of json
I've created a rails-api application and proceeded to secure it using token authentication.我已经创建了一个 rails-api 应用程序并继续使用令牌身份验证来保护它。
I've set a before_filter
that is calling a method which uses authenticate_or_request_with_http_token
.我已经设置了一个
before_filter
,它正在调用一个使用authenticate_or_request_with_http_token
的方法。 Everything is working fine but, when the authentication is incorrect i'm getting an html response.一切正常,但是,当身份验证不正确时,我会收到 html 响应。
How can I define what format the response should be?如何定义响应的格式?
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
By including ActionController::HttpAuthentication::Token::ControllerMethods
you include several methods, amongst others request_http_token_authentication
which is simply a wrapper around Token.authentication_request
.通过包含
ActionController::HttpAuthentication::Token::ControllerMethods
您可以包含多种方法,其中request_http_token_authentication
只是Token.authentication_request
的包装器。 That #authentication_request
-method is the culprit and sends the plain text (not HTML as your question suggests) as follows: #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
The trick is to override request_http_token_authentication
in your ApplicationController
to not call Token.authentication_request
but to set the correct status and headers and then render JSON instead.诀窍是覆盖
ApplicationController
request_http_token_authentication
以不调用Token.authentication_request
而是设置正确的状态和标头,然后呈现 JSON。 Add this to your ApplicationController
:将此添加到您的
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
From Rails 5, the authenticate_or_request_with_http_token method allows a second parameter with a custom message, so you could just do:从 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.