Saturday, August 11, 2012

password protected directory in tomcat

Sponsored Links

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:

Add user, password and role in conf/tomcat-users.xml

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:

In the webapps/examples/WEB-INF/web.xml specify role, method and urls.

<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

Now goto browser and check. You can see it prompt for credentials as this.
password protected directory in tomcat
password protected directory in tomcat 


Recommended Reading

1. Web Application Architecture: Principles, Protocols and Practices
2. The Accidental Administrator: Linux Server Step-by-Step Configuration Guide
3. Apache Tomcat 7
4. Run Your Own Web Server Using Linux & Apache
5. Professional Apache Tomcat 6 (WROX Professional Guides)
6. Web Server Administration (Web Warrior)

Sponsored Links

No comments:

Post a Comment

Be nice. That's all.