The fastest way to configure authentication in Tomcat is Basic Authentication. However, it is one of the weakest forms of authentication, and we should not use it in real-life applications. Although we should not use Basic Authentication, it is still worth learning how to do it. This post shows how to use Basic Authentication in a web application in Java using Tomcat.
Requirements
This post uses the following items.
- Tomcat 8.5.37
- Open JDK 1.8.0_192
- Windows 10
Configure Roles And Users Tomcat
Suppose we have an old-school JSP/Servlet application; we need to modify the conf/tomcat-users.xml file with the following roles and users. Note that the roles and users are hard-coded. However, we could configure Tomcat to use data from a database for Basic Authentication instead of an XML file.
1 2 3 4 5 6 7 8 | <tomcat-users xmlns="http://tomcat.apache.org/xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd" version="1.0"> <role rolename="role1"/> <role rolename="role2"/> <user username="karl" password="password" roles="role1, role2"/> </tomcat-users> |
In the XML, we define two roles – role1 and role2. We also define a user belonging to those two roles.
Configure Web Application For Tomcat Basic Authentication
Then, we modify the web.xml to use the security-constraint and login-config elements, among other things, as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?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_4_0.xsd" version="4.0"> <security-constraint> <web-resource-collection> <web-resource-name>all-protected</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>role1</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>Turreta.com</realm-name> </login-config> </web-app> |
Here we wanted to restrict the whole application to only users with the role role1. Moreover, we use CONFIDENTIAL for the transport-guarantee element to force SSL authentication.
We can check the Tomcat Basic Authentication documentation for more configuration options.