This post goes into the nitty grittys of setting up user authentication in Jetty using realms. I had a tough time getting it done. So thought would share the details here.

Let us say that only users who have the role user assigned to them should be able to access the page foo.jsp. Let us now go about doing this in Jetty. Your web.xml should have this.

<security-role>
<role-name>user</role-name>
</security-role>

<login-config>
<realm-name>Auth</realm-name>
</login-config>

<security-constraint>
<web-resource-collection>
<web-resource-name>File Upload</web-resource-name>
<url-pattern>/foo.jsp</url-pattern>
</web-resource-collection>

<auth-constraint>
<role-name>user</role-name>
</auth-constraint>
</security-constraint>

Your jetty.xml should have the following

<Set name=”UserRealms”>
<Array type=”org.mortbay.jetty.security.UserRealm”>
<Item>
<New class=”org.mortbay.jetty.security.HashUserRealm”>
<Set name=”name”>Auth</Set>
<Set name=”config”><SystemProperty name=”jetty.home” default=”.”/>               /etc/realm.properties</Set>
<Set name=”refreshInterval”>0</Set>
</New>
</Item>
</Array>
</Set>

Let us add one user having user name foo and password bar whose role is admin to realm.properties file. Add the following line to realm.properties file.

foo: bar,user

That is it. You are all set to go. We have put the password in plain text format. But a MD5 hash of the password can also be used. The realm name in web.xml file should exactly match the one in jetty.xml file. In our case it is Auth. This is how Jetty maps the realms. Also the role names in web.xml file should exactly match the one in realm.properties file. In our case, it is user. Be careful to see that they are of the same case. If, in web.xml, you have defined the role as User and in properties file you have given it as user, it will not work.

In web.xml, do not include the context name of the application in url pattern. Say, your web application context name is SomeWorldChangingApp. If you have put the url in web.xml as below

<url-pattern>/SomeWorldChangingApp/foo.jsp</url-pattern>

Will not work. The correct pattern is

<url-pattern>/foo.jsp</url-pattern>

Jetty also provides JDBC realm which I have not explored.

Advertisements