问题
I'm struggling myself trying to change that default message once you insert invalid credentials as username:password on rails using
.authenticate_or_request_with_http_basic
For example if I make a curl request on a method that need this authentication, once I insert the wrong username and password it returns HTTP Basic: Access denied.
So, in this case I would like to be able to customize this message with a specific XML formatted string, (just like twitter API does). Is that possible?
Thanks in advance
回答1:
If you want to customize the message in the login prompt, just pass the message to the method call.
authenticate_or_request_with_http_basic "My custom message" do |user_name, password|
user_name == USER_NAME && password == PASSWORD
end
If you want to customize the final error message, according to Rails 2.3.4 source code you can do this only for the HTTP Digest authentication.
def authentication_request(controller, realm, message = nil)
message ||= "HTTP Digest: Access denied.\n"
authentication_header(controller, realm)
controller.__send__ :render, :text => message, :status => :unauthorized
end
The Basic Authentication has the error message hard-coded into the method.
def authentication_request(controller, realm)
controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
controller.__send__ :render, :text => "HTTP Basic: Access denied.\n", :status => :unauthorized
end
来源:https://stackoverflow.com/questions/1745452/rails-authenticate-or-request-with-http-basic-custom-access-denied-message