Tuesday, February 1, 2011

JavaLite HTTP gets Basic HTTP Authentication

While I'm not a big proponent of Basic HTTP Authentication, some people find it useful. Usually when you use internal services, you do not need any authentication - you use firewalls and other restrictions.

When we expose services to partners, we usually define some sort of token based authentication that is application - specific. However, the JavaLite HTTP package being general purpose HTTP client needed Basic Auth.

The new method I added is basic(user, password), here is a sample of code using basic authentication:

Get get = Http.get("http://localhost:8080/manager/html").basic("tomcat", "tomcat");
System.out.println(get.text());
System.out.println(get.headers());
System.out.println(get.responseCode());

I used Tomcat 6 to test against, and it worked just fine after simple Tomcat configuration:

<tomcat-users>
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat,manager"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
</tomcat-users>

What you see above is tomcat-users.xml file, where I uncommented all XML and added a "manager" role to "tomcat" user.

As usual, I like it when: simple things are simple.

Enjoy,

Igor