How To Enable HSTS Header? How to Implement custom HSTS Filter in Java with Examples?


A Quick Guide to Enable HTTP Strict Transport Security (HSTS) and Different Ways to add HSTS in Tomcat 8 with a custom filter in java, Testing Strict-Transport-Security header. For websites in web.config.

1. Overview:

In this post, We'll learn how to enable/add HTTP Strict Transport Security (HSTS) Header to Tomcat 8 using a built-in filter. And also discuss how to add custom HSTS filter in a java web application.

HSTS | How To Setup Strict Transport Security (HSTS)

Learn Enabling/Adding HTTP Strict Transport Security (HSTS) Header to a Website in Tomcat or Any Server

As well as a solution to add HSTS to any web-site using web.config.

At last, will talk about the testing methodology to make sure HSTS is enabled for a website.

About HSTS:

HTTP Strict Transport Security (HSTS) instructs web browsers to only use secure connections for all future requests when communicating with a web site. Doing so helps prevent SSL protocol attacks, SSL stripping, cookie hijacking, and other attempts to circumvent SSL protection.

Enabling HSTS Header

Enabling HTTP Strict Transport Security (HSTS) for Tomcat 8:

HSTS is abbreviated as HTTP Strict Transport Security. HTTP Strict Transport Security (HTTP ) is a web security policy mechanism that helps to protect websites against protocol downgrade attacks and cookie hijacking.

Most of the companies do the Security vulnerability scan for your application and maybe saying missing HTTP Strict Transport Security is missing as part of the response. Please add an HTTP header to the response.

Adding HTTP Strict Transport Security(HSTS) in java, Tomcat

how to implement missing hsts header version

This can be done in two ways.

1) Tomcat 8 built-in filter
2) Changes to web.config
3) Implementing Custom Filter in java
4) How to test HSTS is enabled for a website.

2.  Tomcat 8 built-in filter for HSTS

Before doing this, You must enable HTTPS redirect protocol in the server. This post designed for the tomcat server.
When we receive the HTTP request then internally need to redirect to HTTPS. below is the configuration for this.

2.1 tomcat8/conf/server.xml

<Connector executor="tomcatThreadPool"
           port="8080" protocol="HTTP/1.1"
           redirectPort="8443" /> 

2.2 Tomcat server configuration:

If your application is deployed in tomcat 8 server, then there is a built-in filter that will fulfill all your needs. HttpHeaderSecurityFilter class is provided by the Tomcat server. We must have tomcat version 8 to enable this feature.

Built in filter: org.apache.catalina.filters.HttpHeaderSecurityFilter

HSTS_HEADER_NAME = "Strict-Transport-Security"; is a predefined value and can not be changed by the developer. This constant is part of the HttpHeaderSecurityFilter.

Below are the parameters which can be configured in web.xml file.

  private boolean hstsEnabled;
  private int hstsMaxAgeSeconds;
  private boolean hstsIncludeSubDomains;
  private boolean hstsPreload;
  private String hstsHeaderValue;

Add the following configuration in tomcat8/conf/web.xml file which is loaded during server startup.



After adding, we should be now able to see in the response header.

Strict-Transport-Security: max-age=31536000; includeSubDomains

The main advantage of configuring at the server level is this is applicable for all the application that deployed in this server and no need to configure for each application.

The drawback is we must take note that while upgrading the tomcat server, we must do this change otherwise way be open for attackers.

3. Adding HSTS Header to Websites in web.config

Some websites and blogs say that to implement HSTS in IIS7+ you should just add the CustomHeader require for HSTS like this in your web.config. This is NOT correct:

            <add name="Strict-Transport-Security" value="max-age=31536000"/>

This isn't technically to spec. The problem here is that you're sending the header ALWAYS even when you're not under HTTPS.

Note the first rule directs to a secure location from an insecure one. The second one adds the HTTP header for Strict-Transport-Security. The only thing I might change would be to formally canonicalize the www. prefix versus a naked domain.

<?xml version="1.0" encoding="UTF-8"?>
                <rule name="HTTP to HTTPS redirect" stopProcessing="true">
                    <match url="(.*)" />
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
                        redirectType="Permanent" />
                <rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
                    <match serverVariable="RESPONSE_Strict_Transport_Security"
                        pattern=".*" />
                        <add input="{HTTPS}" pattern="on" ignoreCase="true" />
                    <action type="Rewrite" value="max-age=31536000" />

4. Implementing HSTS Custom Filter in Java

We can write our own filter to add HSTS in response to every request. In some cases, 1st methodology will not work even if we are using tomcat 8+ version.

Our custom filter class must implements interface javax.servlet.Filter and provide implementations for init(), doFilter() , destroy() methods.

I have written a custom filter named HSTSFilter class and should be configured in the web.xml file. See the below two steps for custom HSTS filter implementation.

4.1 Custom HSTS Filter Class 

package com.java.w3shools;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HSTSFilter implements Filter {
 private static final String HEADER_NAME = "Strict-Transport-Security";
 private static final String MAX_AGE_DIRECTIVE = "max-age=%s";
 private static final String INCLUDE_SUB_DOMAINS_DIRECTIVE = "includeSubDomains";
 private static final Logger logger = LoggerFactory.getLogger(HSTSFilter.class);

 private int maxAgeSeconds = 0;
 private boolean includeSubDomains = false;
 private String directives;

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
   throws IOException, ServletException {
  logger.debug("request.isSecure() :: " + request.isSecure());
  System.out.println("request.isSecure() :: " + request.isSecure());

  if (request.isSecure() && response instanceof HttpServletResponse) {
   HttpServletResponse res = (HttpServletResponse) response;
   res.addHeader(HEADER_NAME, this.directives);
  chain.doFilter(request, response);

 public void init(FilterConfig filterConfig) throws ServletException {
  maxAgeSeconds = Integer.parseInt(filterConfig.getInitParameter("maxAgeSeconds"));
  includeSubDomains = "true".equals(filterConfig.getInitParameter("includeSubDomains"));

  if (this.maxAgeSeconds <= 0) {
   throw new ServletException("Invalid maxAgeSeconds value :: " + maxAgeSeconds);

  this.directives = String.format(MAX_AGE_DIRECTIVE, this.maxAgeSeconds);
  if (this.includeSubDomains) {
   this.directives += (" ; " + INCLUDE_SUB_DOMAINS_DIRECTIVE);
  System.out.println("directives :: "+directives);

 public void destroy() {

4.2 Web.xml:

After creating our HSTSFilter then it must be configured in web.xml as below.



5. HSTS Testing

How to test HSTS is enabled or not?

Implementing HSTS is one challenging task and the next testing is another challenging part.

How to test HSTS changes that are applied to the web application?

There are mainly three ways.

5.1 Using the UNIX curl command

curl -s -D-  www.domain-name.com | grep Strict

Result expected:

Eg. curl -s -D-  http://localhost:8080/HSTSFilterDemo/index.html | grep Strict


5.2 Chrome extension Postman 

Postman is a free add on in chrome browser. The result would be as below.


5.3 Using third party website

There are many websites that check for HSTS is enabled for a website. Here are some examples of websites.


6. Conclusion

In this tutorial, We have seen what is HSTS and how to implement using a tomcat built-in filter and custom HSTS filter.

Next, Seen a solution to add HSTS to any web-site using web.config in IIS7 servers.

In the further article, we discussed testing whether strict-transport-security is added as part of a response or not.

The complete project source code showed in this article is available over GitHub.





About Us

Author: Venkatesh - I love to learn and share the technical stuff.

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
JavaProgramTo.com: How To Enable HSTS Header? How to Implement custom HSTS Filter in Java with Examples?
How To Enable HSTS Header? How to Implement custom HSTS Filter in Java with Examples?
A Quick Guide to Enable HTTP Strict Transport Security (HSTS) and Different Ways to add HSTS in Tomcat 8 with a custom filter in java, Testing Strict-Transport-Security header. For websites in web.config.
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content