How to Authenticate and Manage Users
The Servlet API requires the container to offer a rudimentary security system which should be sufficient for most internal and corporate sites, but not for consumer-oriented internet sites (more).
- Authentication mechanisms:
- User management is container-specific (more). In any case, a web application can only get the request user's name and role, but not any additional information, from the container.
- Security is mostly role-based. A web application declares security roles in its web.xml, and the application defines the rights each role has. Each user can be in one or more roles. The mapping between users and their roles is container specific and must be done by an administrator or the deployer.
In order to use the security system, the application needs to declare roles and authentication mechanism in its web.xml deployment descriptor.
Declaring Roles
All roles used by the application must be declared using the <security-role> element in the web.xml deployment descriptor.
<security-role> <description>Administrator Role</description> <role-name>admin</role-name> </security-role> <security-role> <description>Privileged User</description> <role-name>privileged</role-name> </security-role> <security-role> <description>Guest User</description> <role-name>guest</role-name> </security-role>
Basic Authentication
For basic authentication, add this to your web.xml deployment descriptor:
<login-config> <auth-method>BASIC</auth-method> <realm-name>My Realm</realm-name> <!-- shown to the user --> </login-config>
Digest Authentication
DIGEST authentication is optional and not supported by older browsers, but more secure than BASIC:
<login-config> <auth-method>DIGEST</auth-method> </login-config>
Form-based Authentication
For FORM authentication you need to create two pages containing the actual authentication screens:
<login-config> <auth-method>FORM</auth-method> <form-login-config> <form-login-page>/login.jsp</form-login-page> <!-- login form --> <form-error-page>/login-error.html</form-error-page> <!-- error page --> </form-login-config> </login-config>
The login page must have a HTML form using the POST method, with a form action 'j_security_check' and two fields 'j_username' and 'j_password'. The form looks like this:
<form method="POST" action="j_security_check">
<input type="text" name="j_username" />
<input type="password" name="j_password" />
</form> SSL Client Authentication
To require authentication with a SSL client certificate, add this in your web.xml deployment descriptor:
<login-config> <auth-method>CLIENT-CERT</auth-method> </login-config>
When a client authenticated itself with a SSL client certificate, you can retrieve the certificate chain from the request attribute javax.servlet.request.X509Certificate. It contains an array of java.security.cert.X509Certificate instances.

