![](/img/trans.png)
[英]authenticate_or_request_with_http_token always returning false with AFNetworking
[英]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.