Last editor: Dave Cherry, last modified: Aug 18, 2008
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:
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.