[[servlet-headers]]
= Security HTTP Response Headers

<<headers,Security HTTP Response Headers>> can be used to increase the security of web applications.
This section is dedicated to servlet based support for Security HTTP Response Headers.

[[servlet-headers-default]]
== Default Security Headers

Spring Security provides a <<headers-default,default set of Security HTTP Response Headers>> to provide secure defaults.
While each of these headers are considered best practice, it should be noted that not all clients utilize the headers, so additional testing is encouraged.

You can customize specific headers.
For example, assume that you want the defaults except you wish to specify `SAMEORIGIN` for <<servlet-headers-frame-options,X-Frame-Options>>.

You can easily do this with the following Java Configuration:

.Customize Default Security Headers with Java Configuration
====
[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
		WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) {
		http
			// ...
			.headers(headers ->
				headers
					.frameOptions(frameOptions ->
						frameOptions.sameOrigin()
					)
			);
	}
}
----
====

Alternatively, if you are using Spring Security XML Configuration, you can use the following:

.Customize Default Security Headers with XML Configuration
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<frame-options policy="SAMEORIGIN" />
	</headers>
</http>
----
====

If you do not want the defaults to be added and want explicit control over what should be used, you can disable the defaults.
An example for both Java and XML based configuration is provided below:

If you are using Spring Security's Java Configuration the following will only add <<headers-cache-control,Cache Control>>.

[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// ...
			.headers(headers ->
				headers
					// do not use any default headers unless explicitly listed
					.defaultsDisabled()
					.cacheControl(withDefaults())
			);
	}
}
----

The following XML will only add <<headers-cache-control,Cache Control>>.

[source,xml]
----
<http>
	<!-- ... -->

	<headers defaults-disabled="true">
		<cache-control/>
	</headers>
</http>
----


If necessary, you can disable all of the HTTP Security response headers with the following Java Configuration:

[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// ...
			.headers(headers ->
				headers.disable()
			);
	}
}
----

If necessary, you can disable all of the HTTP Security response headers with the following XML configuration below:

[source,xml]
----
<http>
	<!-- ... -->

	<headers disabled="true" />
</http>
----

[[servlet-headers-cache-control]]
== Cache Control

Spring Security includes <<headers-cache-control,Cache Control>> headers by default.

However, if you actually want to cache specific responses, your application can selectively invoke https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#setHeader(java.lang.String,java.lang.String)[HttpServletResponse.setHeader(String,String)] to override the header set by Spring Security.
This is useful to ensure things like CSS, JavaScript, and images are properly cached.

When using Spring Web MVC, this is typically done within your configuration.
Details on how to do this can be found in the https://docs.spring.io/spring/docs/5.0.0.RELEASE/spring-framework-reference/web.html#mvc-config-static-resources[Static Resources] portion of the Spring Reference documentation

If necessary, you can also disable Spring Security's cache control HTTP response headers.

.Cache Control Disabled with Java Configuration
====
[source,java]
----
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) {
		http
			// ...
			.headers(headers ->
				headers.cacheControl(cache ->
					cache.disabled()
				)
			);
	}
}
----
====

Similarly, you can use the <<nsa-cache-control,<cache-control>>> element to disable it:

.Cache Control Disabled with XML
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<cache-control disabled="true"/>
	</headers>
</http>
----
====

[[servlet-headers-content-type-options]]
== Content Type Options

Spring Security includes <<headers-content-type-options,Content-Type>> headers by default.
However, you can disable it in Java Configuration with:

.Content Type Options Disabled with Java Configuration
====
[source,java]
----
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends
		WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) {
		http
			// ...
			.headers(headers ->
				headers.contentTypeOptions(contentType ->
					contentType.disabled()
				)
			);
	}
}
----
====

Similarly, you can use the <<nsa-content-type-options,<content-type-options>>> element to disable it:

.Content Type Options Disabled with XML
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<content-type-options disabled="true"/>
	</headers>
</http>
----
====

[[servlet-headers-hsts]]
== HTTP Strict Transport Security (HSTS)

Spring Security provides the <<headers-hsts,Strict Transport Security>> header by default.
However, you can customize the results explicitly.
For example, the following is an example of explicitly providing HSTS with Java Configuration:

.Strict Transport Security with Java Configuration
====
[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// ...
			.headers(headers ->
				headers
					.httpStrictTransportSecurity(hsts ->
						hsts
							.includeSubDomains(true)
							.preload(true)
							.maxAgeInSeconds(31536000)
					)
			);
	}
}
----
====

Similarly, you can explicitly provide HSTS with XML configuration using the <<nsa-hsts,<hsts>>> element as shown below:


.Strict Transport Security with XML Configuration
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<hsts
			include-subdomains="true"
			max-age-seconds="31536000"
			preload="true" />
	</headers>
</http>
----
====

[[servlet-headers-hpkp]]
== HTTP Public Key Pinning (HPKP)
For passivity reasons, Spring Security provides servlet support for <<headers-hpkp,HTTP Public Key Pinning>> but it is <<headers-hpkp-deprecated,no longer recommended>>.

You can enable HPKP headers with Java Configuration:

.HTTP Public Key Pinning with Java Configuration
====
[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// ...
			.headers(headers ->
				headers
					.httpPublicKeyPinning(hpkp ->
						hpkp
							.includeSubDomains(true)
							.reportUri("https://example.net/pkp-report")
							.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=")
					)
			);
	}
}
----
====

Similarly you can enable HPKP headers using the <<nsa-hpkp,<hpkp>>> element as shown below:

.HTTP Public Key Pinning with XML Configuration
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<hpkp
			include-subdomains="true"
			report-uri="https://example.net/pkp-report">
			<pins>
				<pin algorithm="sha256">d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=</pin>
				<pin algorithm="sha256">E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=</pin>
			</pins>
		</hpkp>
	</headers>
</http>
----
====


[[servlet-headers-frame-options]]
== X-Frame-Options

By default, Spring Security disables rendering within an iframe using <<headers-frame-options,X-Frame-Options>>.

You can customize frame options to use the same origin within Java Configuration using the following:

.X-Frame-Options: SAMEORIGIN with Java Configuration
====
[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// ...
			.headers(headers ->
				headers
					.frameOptions(frameOptions ->
						frameOptions
							.sameOrigin()
					)
			);
	}
}
----
====

Alternatively, you can use <<nsa-frame-options,frame-options>> element within XML configuration:

.X-Frame-Options: SAMEORIGIN with XML Configuration
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<frame-options
		policy="SAMEORIGIN" />
	</headers>
</http>
----
====


[[servlet-headers-xss-protection]]
== X-XSS-Protection

By default, Spring Security instructs browsers to block reflected XSS attacks using the <<headers-xss-protection,X-XSS-Protection header>.
However, you can change this default.
For example, the following Java Configuration specifies that Spring Security should no longer instruct browsers to block the content:

.X-XSS-Protection Customization with Java Configuration
====
[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// ...
			.headers(headers ->
				headers
					.xssProtection(xssProtection ->
						xssProtection
							.block(false)
					)
			);
	}
}
----
====

Similarly, the following XML configuration specifies that Spring Security should no longer instruct browsers to block the content:

.X-XSS-Protection Customization with XML Configuration
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<xss-protection block="false"/>
	</headers>
</http>
----
====


[[servlet-headers-csp]]
== Content Security Policy (CSP)

Spring Security does not add <<headers-csp,Content Security Policy>> by default, because a reasonable default is impossible to know without context of the application.
The web application author must declare the security policy(s) to enforce and/or monitor for the protected resources.

For example, given the following security policy:

.Content Security Policy Example
====
[source,http]
----
Content-Security-Policy: script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/
----
====

You can enable the CSP header using Java configuration as shown below:

.Content Security Policy Java Configuration
====
[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) {
		http
			// ...
			.headers(headers ->
				headers
					.contentSecurityPolicy(csp ->
						csp
							.policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
					)
			);
	}
}
----
====

The same can be done using XML configuration with the <<nsa-content-security-policy,<content-security-policy>>> element as shown below:

.Content Security Policy Java Configuration
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<content-security-policy
			policy-directives="script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/" />
	</headers>
</http>
----
====

To enable the CSP `report-only` header, provide the following Java configuration:

.Content Security Policy Report Only Java Configuration
====
[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
		WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// ...
			.headers(headers ->
				headers
					.contentSecurityPolicy(csp ->
						csp
							.policyDirectives("script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/")
							.reportOnly()
					)
			);
	}
}
----
====

The same can be achieved with XML configuration using:

.Content Security Policy XML Configuration
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<content-security-policy
			policy-directives="script-src 'self' https://trustedscripts.example.com; object-src https://trustedplugins.example.com; report-uri /csp-report-endpoint/"
			report-only="true" />
	</headers>
</http>
----
====

[[servlet-headers-referrer]]
== Referrer Policy

Spring Security does not add <<headers-referrer,Referrer Policy>> headers by default.
You can enable the Referrer Policy header using Java configuration as shown below:

.Referrer Policy Java Configuration
====
[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) {
		http
			// ...
			.headers(headers ->
				headers
					.referrerPolicy(referrerPolicy ->
						referrerPolicy
							.policy(ReferrerPolicy.SAME_ORIGIN)
					)
			);
	}
}
----
====

You can enable the Referrer-Policy header using XML configuration with the <<nsa-referrer-policy,<referrer-policy>>> element as shown below:

.Referrer Policy XML Configuration
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<referrer-policy policy="same-origin" />
	</headers>
</http>
----
====


[[servlet-headers-feature]]
== Feature Policy

Spring Security does not add <<headers-feature,Feature Policy>> headers by default.
The following `Feature-Policy` header:

.Feature-Policy Example
====
[source]
----
Feature-Policy: geolocation 'self'
----
====

can enable the Feature Policy header using Java configuration as shown below:

.Feature-Policy Java Configuration
====
[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// ...
			.headers(headers ->
				headers
					.featurePolicy("geolocation 'self'")
			);
	}
}
----
====


Alternatively, you can enable the Feature-Policy header using XML configuration with the <<nsa-feature-policy,<feature-policy>>> element as shown below:

.Feature-Policy XML Configuration
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<feature-policy policy-directives="geolocation 'self'" />
	</headers>
</http>
----
====

[[servlet-headers-clear-site-data]]
== Clear Site Data

Spring Security does not add <<headers-clear-site-data,Clear-Site-Data>> headers by default.
The following Clear-Site-Data header:

.Clear-Site-Data Example
====
----
Clear-Site-Data: "cache", "cookies"
----
====

can be sent on log out with the following configuration:

.Clear-Site-Data Java Configuration
====
[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// ...
			.logout()
				.addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(CACHE, COOKIES)));
	}
}
----
====

[[servlet-headers-custom]]
== Custom Headers
Spring Security has mechanisms to make it convenient to add the more common security headers to your application.
However, it also provides hooks to enable adding custom headers.

[[servlet-headers-static]]
=== Static Headers
There may be times you wish to inject custom security headers into your application that are not supported out of the box.
For example, given the following custom security header:

[source]
----
X-Custom-Security-Header: header-value
----

The headers could be added to the response using Java Configuration as shown in the following:

.StaticHeadersWriter Java Configuration
====
[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// ...
			.headers(headers ->
				headers
					.addHeaderWriter(new StaticHeadersWriter("X-Custom-Security-Header","header-value"))
			);
	}
}
----
====

When using the XML namespace, these headers can be added to the response using the <<nsa-header,<header>>> element as shown below:

.StaticHeadersWriter XML Configuration
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<header name="X-Custom-Security-Header" value="header-value"/>
	</headers>
</http>
----
====


[[servlet-headers-writer]]
=== Headers Writer
When the namespace or Java configuration does not support the headers you want, you can create a custom `HeadersWriter` instance or even provide a custom implementation of the `HeadersWriter`.

Let's take a look at an example of using an custom instance of `XFrameOptionsHeaderWriter`.
If you wanted to explicitly configure <<servlet-headers-frame-options>> it could be done with the following Java Configuration:

.Headers Writer Java Configuration
====
[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			// ...
			.headers(headers ->
				headers
					.addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN))
			);
	}
}
----
====

Alternatively, we could use the <<nsa-header-ref,ref>> attribute for XML based configuration:

.Headers Writer XML Configuration
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<header ref="frameOptionsWriter"/>
	</headers>
</http>
<!-- Requires the c-namespace.
See https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-c-namespace
-->
<beans:bean id="frameOptionsWriter"
	class="org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter"
	c:frameOptionsMode="SAMEORIGIN"/>
----
====

[[headers-delegatingrequestmatcherheaderwriter]]
=== DelegatingRequestMatcherHeaderWriter

At times you may want to only write a header for certain requests.
For example, perhaps you want to only protect your log in page from being framed.
You could use the `DelegatingRequestMatcherHeaderWriter` to do so.

An example of using `DelegatingRequestMatcherHeaderWriter` in Java Configuration can be seen below:

.DelegatingRequestMatcherHeaderWriter Java Configuration
====
[source,java]
----
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		RequestMatcher matcher = new AntPathRequestMatcher("/login");
		DelegatingRequestMatcherHeaderWriter headerWriter =
			new DelegatingRequestMatcherHeaderWriter(matcher,new XFrameOptionsHeaderWriter());
		http
			// ...
			.headers(headers ->
				headers
					.frameOptions(frameOptions ->
						frameOptions.disable()
					)
					.addHeaderWriter(headerWriter)
			);
	}
}
----
====

The same can be achieved with XML based configuration:

.DelegatingRequestMatcherHeaderWriter XML Configuration
====
[source,xml]
----
<http>
	<!-- ... -->

	<headers>
		<frame-options disabled="true"/>
		<header ref="headerWriter"/>
	</headers>
</http>

<beans:bean id="headerWriter"
	class="org.springframework.security.web.header.writers.DelegatingRequestMatcherHeaderWriter">
	<beans:constructor-arg>
		<bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher"
			c:pattern="/login"/>
	</beans:constructor-arg>
	<beans:constructor-arg>
		<beans:bean
			class="org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter"/>
	</beans:constructor-arg>
</beans:bean>
----
====

