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:

<realm-name>Example Form-Based Authentication Area</realm-name>

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):

<display-name>Example Security Constraint</display-name>
<web-resource-name>Protected Area</web-resource-name>
<!-- Define the context-relative URL(s) to be protected -->
<!-- If you list http methods, only those methods are protected -->
<!-- Anyone with one of the listed roles may access this area -->

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: