views:

503

answers:

1

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  A: 

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
Simone Carletti
Thanks weppos, I've checked that before too, but the thing is in this case I'm using BCrypt as encryption for my passwords, so I'm not sure if I can use Http Digest Auth with it, another thing is, Is there any way to override this functions from http basic? I tried without success, because It's kind weird since it looks like that Twitter API uses the Http Basic as well and they were able to configure the final error message.
ludicco
Yes, with monkey patching you can override almost everything... but this is not always a good idea.
Simone Carletti