Rails - authenticate_or_request_with_http_basic custom “access denied” message

霸气de小男生 提交于 2019-12-07 20:17:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!