Rails 2.x http basic authentication
I'm trying to get basic http authentication working on my Rails app. I'm offering a simple REST interface served by a Ra开发者_StackOverflowils server, only xml/json output.
Every method needs authentication, so I put the authenticate filter in ApplicationController:
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
before_filter :authenticate
protected
def authenticate
authenticate_or_request_with_http_basic do |u, p|
true
end
end
end
Even with having the method return true, I'm receiving a 401 from the server:
$ curl http://127.0.0.1:3000/myresource/1.xml -i
HTTP/1.1 401 Unauthorized
Cache-Control: no-cache
WWW-Authenticate: Basic realm="Application"
X-Runtime: 1
Content-Type: text/html; charset=utf-8
Content-Length: 27
Server: WEBrick/1.3.1 (Ruby/1.9.1/2010-01-10)
Date: Thu, 03 Jun 2010 02:43:55 GMT
Connection: Keep-Alive
HTTP Basic: Access denied.
If I'm explicitly returning true, yet getting served a 401.
you have to specify a login/password pair, even if you don't check them
curl http://127.0.0.1:3000/myresource/1.xml -i -u username:password
If you want to show an error message for XML requests you can write your own before_filter
:
class ApplicationController < ApplicationController::Base
before_filter :authenticate
def authenticate
authentication_procedure = lambda do |username, password|
# test username and password
end
authenticate_with_http_basic(&authentication_procedure) ||
request_http_basic_authentication_or_show_xml_error(&authentication_procedure)
end
def request_http_basic_authentication_or_show_xml_error(&auth_proc)
if request.format == Mime::XML
render :action => '/errors/401'
else
request_http_basic_authentication('My Realm')
end
end
end
Then put something into app/views/errors/401.xml.builder
.
精彩评论