How to protect a web directory with a password? if we are using Apache, we can do it easily with .htaccess. It will prompt user for credentials while entering the directory. But how to protect a directory with password in tomcat web server? In this post we will discuss how to do it with tomcat Realms. This example was tested in tomcat 7 and tomcat 6.
Steps :
1) Add user, password and role in conf/tomcat-users.xml
2) In the webapps/examples/WEB-INF/web.xml specify role, method and urls.
3) Restart Tomcat and check.
Step 1:
in vi conf/tomcat-users.xml
<tomcat-users>
<role rolename=”webadmin”/> //webadmin is the rolename of the users who can access the application
<user username=”randeep” password=”randeep” roles=”webadmin”/>
</tomcat-users>
Step 2:
<security-constraint>
<display-name>Example Security Constraint</display-name>
<web-resource-collection>
<web-resource-name>application</web-resource-name>
<url-pattern>/*</url-pattern> //applicable toall urls in the application
<http-method>DELETE</http-method>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>PUT</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>webadmin</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method> //Authentication type
<realm-name>application</realm-name>
</login-config>
Step 3:
Restart tomcat
/etc/init.d/tomcat restart
or
bin/shutdown.sh
bin/startup.sh
Recent Comments