How to Restrict Access to a Web Application (Declarative Security)
By default, access to web applications is not restricted. If you want to restrict access to your web application or parts thereof, including static content, you need to declare those restrictions in your web.xml deployment descriptor. When a user requests a restricted page, the container will automatically ask her to log in using the mechanism set with <login-config> (see authentication and user management).
The following web.xml snippet allows access to several sub-folders only to users who have either the 'admin' or the 'privileged' role.
<security-constraint> <web-resource-collection> <web-resource-name>Privileged area</web-resource-name> <url-pattern>/restricted/*</url-pattern> <url-pattern>/premium/*</url-pattern> <url-pattern>/dyn/stats/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> <role-name>privileged</role-name> </auth-constraint> </security-constraint>
The user can access the resource if at least one <security-constraint> permits it. Requiring two roles for accessing a resource is not possible with declarative security (but you can do this with programmatic security).
Allowing All Roles
The special role name '*' stands for all declared roles. Unauthenticated users do not have access.
<security-constraint> <web-resource-collection> <web-resource-name>User area</web-resource-name> <url-pattern>/user/*</url-pattern> <url-pattern>/settings/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>*</role-name> <!-- allow all roles --> </auth-constraint> </security-constraint>
Forbid Access to All Roles
If you want to forbid access for all roles (e.g. for data files used by the servlet), leave the <auth-constraint> empty:
<security-constraint> <web-resource-collection> <web-resource-name>Data area</web-resource-name> <url-pattern>/data/*</url-pattern> </web-resource-collection> <auth-constraint> <!-- empty constraint: forbid all access --> </auth-constraint> </security-constraint>
Restricting Access by HTTP Method
By default, a <web-resource-collection> applies to all HTTP methods. You can also limit access by method:
<security-constraint> <web-resource-collection> <web-resource-name>Resource Modification</web-resource-name> <url-pattern>/*</url-pattern> <http-method>DELETE</http-method> <http-method>PUT</http-method> </web-resource-collection> <auth-constraint> <!-- Only admins can delete and put --> <role-name>admin</role-name> </auth-constraint> </security-constraint>

