blog rss feed

Role based security and authentication with Tomcat

Keywords:

Last editor: Dave Cherry, last modified: Aug 18, 2008

Adding authentication to web.xml

In order to add role based security to our web-application, the first thing we need to do is edit web.xml, located in the WEB-INF directory. To start with the web.xml will look something like the file below:

<?xml version="1.0" encoding="UTF-8"?>
<
web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

</
web-app>

A word of warning before we continue, the web.xml document is validated, and items must appear in the right place, for example security data must appear after filters and servlet elements.

Below we start to add the declarative security, we create a role called manager (security-role), and then create a security-constraint that prevents unauthorised access to the secure resources. Within the security constraint element there are two children, web-resource-collection defines which pages are covered by this definition, and auth-constraint defines the role that will be applied.

<?xml version="1.0" encoding="UTF-8"?>
<
web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

<security-role>
<role-name>manager</role-name>
</security-role>

<security-constraint>
<web-resource-collection>
<web-resource-name>management pages</web-resource-name>
<url-pattern>/secure/*</url-pattern>
<url-pattern>/mixed/secure3.jsp</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>manager</role-name>
</auth-constraint>
</security-constraint>
</
web-app>

Above we used url-pattern elements to define the pages that were included in the constraint. Security constaints can use wildcards and below there’s more examples:

  • *.do - all requests ending in .do
  • /somepage.htm - only the exact page /somepage.htm
  • /secure/* - all pages under directory /secure

At this point you can run the application. However, if you click on any secure content you’ll get a HTML 403 error instead of the page. This is because we have not yet defined how to ask the user to authenticate with the server.

<< 1 2 3 4 5 6 >>

Please leave a comment



Search

Blog calendar

blog: previous month September 2010 blog: next month
su mo tu we th fr sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30