Tuesday 8 January 2008

HTTP Authentication for MERB

I've just started working on a new web application. It's going to be quite a simple app but speed and responsiveness is important so I decided to try Merb. I'm going to blog about some of the difficulties and (hopefully) solutions I discover as I go through the process. One of the main problems with MERB is the lack of documentation so hopefully with these blog posts, I can help with that.

First up, HTTP authentication. In the merb.yml it says the following:

# If you want to protect some or all of your app with HTTP basic auth then
# uncomment the following and fill in your credentials you want it to use.
# You will then need to set a 'before' filter in a controller. For example:
# before :basic_authentication
#:basic_auth:
# :username: ezra
# :password: password
# :domain: localhost

All well and good, but what if you want to validate the authentication against a database of users?

Well the answer is to overwrite the authenticated? method in BasicAuthenticationMixin

This is easy to do, in your application.rb, do something like this:

class Application < Merb::Controller
before :basic_authentication

private
def authenticated?
# if you want get the username and password that was inputted via http use:
# username, password = *credentials
# then validate the user by authenticating against a datbase or whatever
# make sure the return value is true or false
end
end


Note: You still have to uncomment the basic_auth configuration in merb.yml. But it doesn't matter what the username/password is there since you'll be overriding them anyways.

3 comments:

sintaxi said...

great to see other playing around with merb. any idea how to kill a http session?

Dermot said...

I just close the browser and reopen it!

sintaxi said...

yeah. it seems that is the only way without hacks. I have decided to do session based authentication for http requests and HTTP for all the other mime types. thanks for the quick response.