Monday, April 06, 2009

Old Dog Learns Old Trick

It's never too late. I needed to add Tomcat's FORM authentication to a webapp. The steps for doing this are surprisingly under-documented. Here are they are:

1. Write a login form page (login.jsp). The form action should point to "j_security_check". The input parameters for the form are "j_username" and "j_password". There are plenty of examples of this.


2. Add the following to your web.xml:

<login-config>
<auth-method>FORM</auth-method>
<realm-name>Example Form-Based Authentication Area</realm-name>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
</form-login-config>
</login-config>

I took this from the jsp-examples/security examples that come with Tomcat.

If you stop here, install your webapp, and try to login by going directly to login.jsp, it will not work. You will get an error like

The requested resource (/mywebapp/j_security_check) is not available

3. You need to also add the following to your webapp's web.xml file (taken from Tomcat's jsp-examples/ again):

<security-constraint>
<display-name>Example Security Constraint</display-name>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<!-- Define the context-relative URL(s) to be protected -->
<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>
</web-resource-collection>
<auth-constraint>
<!-- Anyone with one of the listed roles may access this area -->
<role-name>tomcat</role-name>
<role-name>role1</role-name>
</auth-constraint>
</security-constraint>


This should work. The dirty trick is that you have to let Tomcat's security constraints redirect you to your login page. You can't point your browser to this page directly.

No comments: