This post demonstrates how to use Basic Authentication in a web application in Java using Tomcat.
Requirements
- Tomcat 8.5.37
- Open JDK 1.8.0_192
Users and Roles
Update conf/tomcat-users.xml with the following roles and users.
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> |
Update web.xml
Then, modify web.xml with the following security-constraint and login-config elements.
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.
SSL
The CONFIDENTIAL value for transport-guarantee element forces the authentication process to be done in SSL.
References
- https://tomcat.apache.org/tomcat-8.5-doc/ssl-howto.html