Thursday, July 10, 2008

Basic HTTP authentication in Tomcat

you just need to insert in the <Engine...></Engine> tag of your server configuration file (conf/server.xml) this tag:

  <Realm className="org.apache.catalina.realm.MemoryRealm" />

Once you have done this, you should edit (or create) the conf/tomcat-users.xml file where you will place the name of all the users you wanna give access to, and their "role". A simple example could be this one:
<?xml version='1.0' encoding='utf-8'?>
<role rolename="test"/>
<user username="user" password="pass" roles="test"/>


This has created a role called "test", and a "user" that belongs to that role.

The second step is the standard servlet way to set the authentication, siply adding to your web application descriptor (web.xml) some imformation like, for example:
Protected Site

<!-- This would protect the entire site -->
<url-pattern> /* </url-pattern>
<!-- If you list http methods,
only those methods are protected -->

<http-method> DELETE </http-method>

<http-method> GET </http-method>
<http-method> POST </http-method>
<http-method> PUT </http-method>

<!-- Roles that have access -->
<role-name> test </role-name>



<!-- BASIC authentication -->
<auth-method> BASIC </auth-method>
<realm-name> Example Basic Authentication </realm-name>


<!-- Define security roles -->
<description> Test role </description>
<role-name> test </role-name>

That should be enough to start...

No comments: