Wednesday, August 13, 2014

Enable SSL in Tomcat

This is not about the theory of SSL. Also it is more focused around putting SSL in Tomcat based environment. So the first thing to do is to generate the SSL certificate using the keytool utility coming with Java as follows
$JAVA_HOME/bin/keytool -genkey -alias <your_alias_name> -keyalg RSA -keystore <your_keystore_filename>
You will be prompted for a password. Remember it as it will be needed for configuration. Also for the common name give the domain name for which you eventually want to buy the certificate from the certificate authority.
For certifying your certificate, you need to submit a csr to the certificate authority. The csr can be generated again by using keytool command
$JAVA_HOME/bin/keytool -certreq -keyalg RSA -alias <your_alias_name> -file certreq.csr -keystore <your_keystore_filename>
Now you can go to any certificate authority and submit your CSR. Based on the levels, you might have to go through some administrative process, but than you will be given a certificate.
Once the certificate is there, you need to configure the tomcat for the certificate. For that open in tomcat directory conf/server.xml and change the following lines
<-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
<Connector port="8443" maxThreads="200"
           scheme="https" secure="true" SSLEnabled="true"
           clientAuth="false" sslProtocol="TLS"/>
Now the certificate provided by Certificate authority needs to be installed in the keystore.
For Tomcat download a PCKS #7 format certificate and install the certificate using the keytool command again
keytool -import -alias <alias_name> -trustcacerts -file <certificate_from_ca> -keystore <keystore_file>
Also make sure that your domain DNS servers are mapped to the ip address of where your application is located. This can be done from the admin panel of your domain provider. Than in the server make sure 443 port is opened and you can make either your Tomcat to listen to 443 or redirect the traffic to 8443, where Tomcat listens. In Linux you can do this as follows:
/sbin/iptables -t nat -I PREROUTING --source 0/0 --destination 0/0 -p tcp --dport 443 -j REDIRECT --to-ports 8443
If everything is fine, you will see a green lock when you access your domain.

Now redirect your http port to https. Make sure following line in uncommented in server.xml

<Connector port="8080" protocol="HTTP/1.1" 
               redirectPort="8443" />
If you want everything in Tomcat to redirect to https port than open web.xml in conf directory of tomcat installation and add the following
        <web-resource-name>Protected Context</web-resource-name>
  <!-- auth-constraint goes here if you requre authentication -->
If you want to do it for certain application, then add the above lines in the web.xml of that application.

No comments:

Post a Comment