To enable basic authentication with tomcat we need to tweak 2 xml file.
- tomcat-users.xml in TOMCAT_HOME/conf/
- web.xml in your webapp for which you want to enable basic authentication.
Add following lines of code in tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?> <tomcat-users> <role rolename="tomcat"/> <user username="myname" password="mypassword" roles="tomcat"/> </tomcat-users>
where myname is username and password is the password for the user. You can change the rolename, username, and password as you wish.
In web.xml of you webapp add following lines of code:
<security-constraint> <web-resource-collection> <web-resource-name> Wildcard means whole app requires authentication </web-resource-name> <url-pattern>/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>tomcat</role-name> </auth-constraint> <user-data-constraint> <!-- transport-guarantee can be CONFIDENTIAL, INTEGRAL, or NONE --> <transport-guarantee>NONE</transport-guarantee> </user-data-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> </login-config>
If you see above config we specified role-name. We can define multiple role names in tomcat-user.xml. Each role name will have a different user name and password.
After you done with changes restart tomcat and access your webapp for testing, it should ask for authentication.