Monday, September 22, 2008

Adding HTTP Basic Authorization to GroovyHTTP

A while back, I discovered a great little Groovy utility by Tony Landis called GroovyHTTP which allows you to generate web requests in Groovy. I've used it with great success on a number of projects.

Lately, I've been playing with a neat GTD web app named Tracks, which has a nice RESTful API for adding tasks, etc. To interact with the application via the API, though, you need to be able to authenticate via HTTP Basic authentication, and GroovyHTTP doesn't seem to support that. Since I really want to interact with Tracks on my internal network with Groovy, I've taken a stab at adding HTTP Basic authentication to GroovyHTTP. Of course, I realize that HTTP Basic is not the most secure authentication method (that's an understatement!), but when you need it, you need it.

It really boils down to adding one method to set the user and login on the GroovyHTTP object, then adding a Base64-encoded authorization string to the HTTP request headers. The extra header line ends up looking like this (for the user/password "Aladdin/open sesame"):

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==


To use the modified GroovyHTTP class to access a URL protected by Basic authentication, you can do something like this:

def h = new GroovyHTTP(protectedUrl)
h.setMethod('POST')
h.setAuthorization(login, password)
h.setParam('p1', p1)
h.setParam('p2', p2)


Since I can't find any contact information for Tony Landis on his site, I figured I'd post the Groovy code here since he's released it under the BSD license. The Groovy class is available here: GroovyHTTP with HTTP Basic Authentication. NOTE: It looks like Google Docs has messed up the formatting in the Groovy class. When I get some time, I'll try to neaten it up.

2 comments:

Tony Landis said...

Hi there, thank you for the reference to GroovyHTTP.

kodeninja said...

Hi Jeff, where can I find info about the Tracks RESTFul API? I can't seem to find it on the Tracks website. Also, could you post a sample of how you've used the GroovyHTTP script to connect to Tracks?

Cheers,
-Kodeninja