Servlet API supports FORM login by specification.
Activating it is pretty easy and few lines in your web.xml is enough.
To use a form, just configure a login-config
using the provided FORM auth method:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <login-config> <auth-method>FORM</auth-method> <form-login-config> <form-login-page>/login.html</form-login-page> <form-error-page>/error.html</form-error-page> </form-login-config> </login-config> </web-app>
You can customize the login and error page. The login page is the form (html) you want to use and the error page is the one you see when you try to log in without being able to get authenticated. Path is relative to the webapp.
The form needs to contain the following parameters (or inputs):
– j_username
– j_password
Their meaning are without any surprise the login and password of the user.
The action of the form is on path `/j_security_check`.
A stupid but working login template can be:
<html> <body> <form method="post" action="j_security_check"> Login: <input type="text" name="j_username" /> Password: <input type="password" name="j_password" /> <input type="submit" value="Login"/> </form> </body> </html>
The error page is totally up to you.
Once all this is set up, we can add some constraints on our web application. Let say we want a user to have master role to access /protected/* urls.
To do so, we add a standard security constraint and a role:
<security-constraint> <web-resource-collection> <web-resource-name>protected-resources</web-resource-name> <url-pattern>/protected/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>master</role-name> </auth-constraint> </security-constraint> <security-role> <role-name>master</role-name> </security-role>
And that’s it! Easy right?
Side note: in Tomcat it can also be interesting to set the landingPage
in the FormAuthenticator
.
This will allow you to show a custom page instead of having error responses if a user tries to access to the login page directly.