HowTo: Tomcat exclude URL pattern form the Basic auth

Posted on

Once you setup the basic authentication in some of the case for Image directories or some other public directories  need not to be comes under the authentication.

By adding few security constrain tags to the existing authentication parameters we can exclude any URL pattern from the security

Here is my web.xml looks like

    <description>Matches all pages.</description>
    <description>Matches a few special pages.</description>
  <!-- No auth-constraint has everybody to access! -->
  <description> logged in users </description>
  <realm-name> watcher </realm-name>

The  two security constraints. The first one “Private”  matches all web resources while the second one “Public” only matches the index page and everything below “/public/”.  No order has to be follow for the security-constraint. 

The auth-constraint specifies which users need to allowed access to the matched pttern. The role-name given  that there must to refer a security-role declaration in web.xml and it must also be present in the servlet container’s user database, we also need a login-config definition for authentication method to use

The “Public” security-constraint need not to specify an auth-constraint element, which means everybody has access to the pattern matched, which is exactly we needed.


  <role rolename="authenticated-user" />
  <user username="myusername" password="mypass" roles="authenticated-user" />

Now re-deploy the container.

HowTo: Enable HTTP to HTTPS redirection in tomcat for server under elb.

Posted on Updated on

I have installed Tomcat native method APR which is very lite to handle the serverlet request, For secure the logins, it is better to configure force redirection.

I followed the below methods,  in amazon server.

1, Configure SSL with port redirection in AWS firewall






2, Edit the tomcat configuration for SSL redirection, Modify the below parts in the conf file.


<Connector port="80" protocol="HTTP/1.1"
 redirectPort="443" />

SSL Certifice configuration in APR tomcat native method

 port="443" maxThreads="500"
 scheme="https" secure="true" SSLEnabled="true"
 SSLVerifyClient="optional" SSLProtocol="TLSv1"/>

3, edit the Aplications web.xml for force redirection. webapps/ROOT/WEB-INF/web.xml

<web-resource-name>Protected Context</web-resource-name>
<!-- auth-constraint goes here if you requre authentication -->

Verify :

curl -I
HTTP/1.1 302 Found
Content-length: 0
Date: Fri, 31 Oct 2014 16:33:42 GMT
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=5B5B0B1292597816EA2C5DE89B298F74; Path=/; HttpOnly
Connection: keep-alive


HowTo: Enable URL rewite for tomcat or other servlet container

Posted on Updated on

It is a URL rewrite feature which is most similar to the apache mod_rewrite, we can use the similar rules to apply the rewrite. Ensure that the ‘UrlRewriteFilter‘ JAR file is on your web-application’s classpath.  place the JAR file in your webapp under ‘/WEB-INF/lib’ will do the trick, and if you’ve spent any time at all working with webapps you probably already have a preferred way of doing this. Alternately, you may want to install the JAR file in your servlet container’s ‘/lib’ folder, particularly if you are deploying multiple webapps on your server and you want to have ‘UrlRewriteFilter‘ available to any/all of them automatically.

Download JAR from here

Read more Examples

once you have the ‘UrlRewriteFilter‘ JAR on your webapp’s classpath, the real setup can begin. Open your application’s ‘web.xml‘ file, and add the following filter configuration to your webapp


This will make the serverlet container to redirect the traffic to UrlRewriteFilter.  Note that although it is not discussed on the official site, that ‘logLevel‘ parameter is absolutely essential for filter to be apply for the traffic.

If you finish adding the tags in web.xml, then move to create urlrewrite.xml in the same directory as with the web.xml. Configure the example rules  for  the URL rewrite.

<?xml version="1.0" encoding="utf-8"?>
 <!DOCTYPE urlrewrite PUBLIC "-// UrlRewrite 3.2//EN"
        <name>Domain Name Check</name>
        <condition name="host" operator="notequal"></condition>
        <to type="redirect">$1</to>
        <to type="redirect">%{context-path}/examples</to>

The first rule is for any request tot he application with IP or alternative alias Domain name added in the server has to rewrite to It can be also use to rewite for including www. in the URL .

The second rule is for the redirect the invalid application “test” to  to the examples,

Its looks like this :   –>  . Both the and are in the same server and same webapps



HowTo: Tomcat Logging – log customized with {X-Forwarded-For}

Posted on Updated on

Tomcat is allowing us to track back logs with enamours of information by customizing the log pattern. There is preset patten is available, we can also implement is in single line

I enabled few more information like execution time , request size , cookies etc..

Default tag should be like this

<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"  
               prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>

Common : %{X-Forwarded-For}i %l %u %t “%r” %s %b
Combined : %{X-Forwarded-For}i %l %u %t %r %s %b %{User-Agent}i %{Referer}i %{Cookie}i

You can change either Common or Combined

I have implemented my own pattern like below, so it should more detailed

pattern="%h %{X-Forwarded-For}i %l %u %t  &quot;%r&quot; %s %b  &quot;%{User-Agent}i&quot; &quot;%{Referer}i&quot; &quot;%{Cookie}i&quot; %T"

Access Log pattern new look

----------------------------- - - - [18/Mar/2014:10:52:06 +0530]  "GET /ajax/norm/list/status?ids=23%2C11%2C9%2C7%2C6%2C5%2C2%2C1%2C HTTP/1.1" 200 42  "Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0" "" "JSESSIONID=4FD1DBEB911CD2E19AA4798F9A26DCA8" 0.007
Log Details : : Remote host name (or IP address if resolveHosts is false)
– : X-Forwarded-For – : Remote logical username
– : Remote user that was authenticated
[18/Mar/2014:10:52:06 +0530]  : Date and time, in Common Log Format
GET /ajax/norm/list/…… : First line of the request (method and request URI)
HTTP/1.1 : Request protocol
200 : HTTP status code of the response
42 : Bytes sent, excluding HTTP headers (Content size)
Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0: User Agent : Referer
JSESSIONID=4FD1DBEB911CD2E19AA4798F9A26DCA8 : Cookie header
0.007 : Time taken to process the request, in seconds

Once every thing has been done you can restart the tomcat to make it effect, more options are given below

%a – Remote IP address
%A – Local IP address
%b – Bytes sent, excluding HTTP headers, or ‘-‘ if zero
%B – Bytes sent, excluding HTTP headers
%h – Remote host name (or IP address if resolveHosts is false)
%H – Request protocol
%l – Remote logical username from identd (always returns ‘-‘)
%m – Request method (GET, POST, etc.)
%p – Local port on which this request was received
%q – Query string (prepended with a ‘?’ if it exists)
%r – First line of the request (method and request URI)
%s – HTTP status code of the response
%S – User session ID
%t – Date and time, in Common Log Format
%u – Remote user that was authenticated (if any), else ‘-‘
%U – Requested URL path
%v – Local server name
%D – Time taken to process the request, in millis
%T – Time taken to process the request, in seconds
%I – current request thread name (can compare later with stacktraces)
%f – X-Forwarded-For IP address
%F – X-Forwarded-For address

HowTo: How to setup basic authentication in tomcat

Posted on Updated on

Container-managed authentication methods control how a user’s credentials are verified when a web app’s protected resource is accessed. When a web application uses basic authentication (BASIC in the web.xml file’s auth-method element), Tomcat uses HTTP basic authentication to ask the web browser for a username and password whenever the browser requests a resource of that protected web application. With this authentication method, all passwords are sent across the network in base64-encoded text.

Note: using basic authentication is generally considered insecure because it does not strongly encrypt passwords, unless the site also uses HTTPS or some other form of encryption between the client and the server (for instance, a virtual private network). But, if you’re just starting to use Tomcat, or if you just want to test container-managed security with your web app, basic authentication is easy to set up and test. Just add <security-constraint> and <login-config> elements to your web app’s web.xml file, and add the appropriate <role> and <user> elements to your CATALINA_BASE/conf/tomcat-users.xml file, restart Tomcat, and Tomcat takes care of the rest.

The example below shows a web.xml excerpt from a club membership web site with a members-only subdirectory that is protected using basic authentication. Note that this effectively takes the place of the Apache web server’s .htaccess files.

For app based Basic authentication you have to edit the web.xml in //webapps/Your-app/WEB-INF/web.xml

For ROOT basic auth  CATILINA_HOME/conf/web.xml

web.xml security tags looks like this

             <web-resource-name> Subdir test </web-resource-name>
             <url-pattern> /* </url-pattern>
             <http-method> GET </http-method>
             <http-method> POST </http-method>

             <!-- the same like in your tomcat-users.conf file -->
             <role-name> manager </role-name>

        <auth-method> BASIC </auth-method>
        <realm-name> iTest Web app resources</realm-name>

       <description> </description>
       <role-name> manager </role-name>

tomcat-users.xml uncomment or add new tag for user credentials

  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
  <user username="anand" password="password" roles="manager"/>

script : Start the tomcat as service.

Posted on

This script is used to start the sevrlet container as service, which is using common-daemon for starting java process.

# tomcat Start/Stop the Tomcat servlet container.
# chkconfig: 345 55 55
# description: Tomcat servlet container.
# processname: tomcat
# Small shell script to show how to start/stop Tomcat using jsvc
# If you want to have Tomcat running on port 80 please modify the server.xml
# file:
# <!-- Define a non-SSL HTTP/1.1 Connector on port 80 -->
# <Connector className="org.apache.catalina.connector.http.HttpConnector"
# port="80" minProcessors="5" maxProcessors="75"
# enableLookups="true" redirectPort="8443"
# acceptCount="10" debug="0" connectionTimeout="60000"/>
# Download and install dependency package 
# Source function library.
. /etc/rc.d/init.d/functions

set +x
CATALINA_OPTS='-Xms512M -Xmx1024M'

start() {
echo $"Starting $prog: "
 # Start Tomcat
 $DAEMON_HOME/bin/jsvc \
 -user $TOMCAT_USER \
 -home $JAVA_HOME \
 -Dcatalina.home=$CATALINA_HOME \$TMP_DIR \
 -outfile $CATALINA_HOME/logs/catalina.out \
 -errfile '&1' \
 # To get a verbose JVM
 #-verbose \
 # To get a debug of jsvc.
 #-debug \
stop() {
 echo $"Stopping $prog: "
 # Stop Tomcat
 PID=`cat /var/run/`
 kill $PID
status() {
 if ! $JAVA_HOME/bin/jps -mlvV | grep -v "Jps" > /dev/null
 echo "Stopped : $prog is no not running"
 echo "Running process for tomcat"
 echo "=========================="
 $JAVA_HOME/bin/jps -mlvV | grep -v "Jps"

case "$1" in
 sleep 2
 echo "Usage $0 {start|stop|restart|status}"
 exit 1;;