Wednesday, November 28, 2007

Rails + pubcookie... finally

Well, I've finally gotten Pubcookie authentication working with my Apache + mongrel cluster configuration.  After talking to a guy on the Pubcookie team, he pointed me to this invaluable resource:
http://www.washington.edu/webinfo/case/zope/

It turns out that most of it is unnecessary if you've already followed the instructions for setting up the mod_proxy_balancer as found here.  The missing key to get Pubcookie working was the mod_fba module that is linked in the case above.  Here is what I did to get everything working (after following Coda Hale's process above):

1. Add mod_fba to your Apache setup:
% wget http://rici.ricilake.net/src/mod_fba.c
% apxs -c mod_fba.c
% apxs -i mod_fba.la 

2. Edit httpd.conf to load that module:
LoadModule fba_module modules/mod_fba.so 

3. Add the configuration for FakeBasicAuth to your myapp.common file:
FakeBasicAuthEnable on
FakeBasicAuthType authtype 

4. Since I want the entire app protected by Pubcookie authentication, add the AuthType directive to the myapp.proxy_cluster.conf file to require a login for everything sent to the mongrel cluster: 
<Proxy balancer://mongrel_cluster>
  BalancerMember http://127.0.0.1:8000
  BalancerMember http://127.0.0.1:8001

  AuthType authtype
  require valid-user
  PubcookieAppID "myapp" 
</Proxy>

5. Now, you'll be able to get access to the HTTP_AUTHORIZATION server variable in your ruby code.  This will be in the form of "Basic" followed by the user's login information encoded in Base64.  This line of ruby will extract out the username only for you to use in your app for authentication purposes:
userid = request.env['HTTP_AUTHORIZATION'].split(' ')[1].unpack("m").to_s.split(':')[0]

3 comments:

Todd Sedano said...

Thank you for this excellent post, it was very helpful for me.

In my development environment, I don't have access to pubcookie authentication, how did you go about writing and testing code outside of a production environment?

Matt said...

@todd: That's something I'm working on, but right now, I have two forms of authentication in the app: pubcookie and restful_authentication. So when I'm in development mode, I only login through the non-pubcookie user accounts.

lupus said...

Hi Matt,

Thanks for the signposts. I *almost* have things working the way I want; perhaps you've seen something like what I'm getting and can point me at how to fix it?

About 15% of the time, Pubcookie appears to be intercepting the conversation between an already-logged-in user and the server. It's forwarding the params, so it should be OK, but something along the way is helpfully encoding all the "[" chars as %5B, which (obviously) interferes with recognition at the Rails end.

Seen anything like that?