14. Protection Against Exploits

14.1 Cross Site Request Forgery (CSRF) for Servlet Environments

This section discusses Spring Security’s Cross Site Request Forgery (CSRF) support for servlet environments.

14.1.1 Using Spring Security CSRF Protection

The steps to using Spring Security’s CSRF protection are outlined below:

Use proper HTTP verbs

The first step to protecting against CSRF attacks is to ensure your website uses proper HTTP verbs. This is covered in detail in Safe Methods Must be Idempotent.

Configure CSRF Protection

The next step is to configure Spring Security’s CSRF protection within your application. Spring Security’s CSRF protection is enabled by default, but you may need to customize the configuration. Below are a few common customizations.

Custom CsrfTokenRepository

By default Spring Security stores the expected CSRF token in the HttpSession using HttpSessionCsrfTokenRepository. There can be cases where users will want to configure a custom CsrfTokenRepository. For example, it might be desirable to persist the CsrfToken in a cookie to support a JavaScript based application.

By default the CookieCsrfTokenRepository will write to a cookie named XSRF-TOKEN and read it from a header named X-XSRF-TOKEN or the HTTP parameter _csrf. These defaults come from AngularJS

You can configure CookieCsrfTokenRepository in XML using the following:

Example 14.1. Store CSRF Token in a Cookie with XML Configuration

<http>
    <!-- ... -->
    <csrf token-repository-ref="tokenRepository"/>
</http>
<b:bean id="tokenRepository"
    class="org.springframework.security.web.csrf.CookieCsrfTokenRepository"
    p:cookieHttpOnly="false"/>

[Note]Note

The sample explicitly sets cookieHttpOnly=false. This is necessary to allow JavaScript (i.e. AngularJS) to read it. If you do not need the ability to read the cookie with JavaScript directly, it is recommended to omit cookieHttpOnly=false to improve security.

You can configure CookieCsrfTokenRepository in Java Configuration using:

Example 14.2. Store CSRF Token in a Cookie with Java Configuration

@EnableWebSecurity
public class WebSecurityConfig extends
        WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) {
        http
            .csrf(csrf ->
                csrf
                    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            );
    }
}

[Note]Note

The sample explicitly sets cookieHttpOnly=false. This is necessary to allow JavaScript (i.e. AngularJS) to read it. If you do not need the ability to read the cookie with JavaScript directly, it is recommended to omit cookieHttpOnly=false (by using new CookieCsrfTokenRepository() instead) to improve security.

Disable CSRF Protection

CSRF protection is enabled by default. However, it is simple to disable CSRF protection if it makes sense for your application.

The XML configuration below will disable CSRF protection.

Example 14.3. Disable CSRF XML Configuration

<http>
    <!-- ... -->
    <csrf disabled="true"/>
</http>

The Java configuration below will disable CSRF protection.

Example 14.4. Disable CSRF Java Configuration

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends
        WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) {
        http
            .csrf(csrf ->
                csrf.disable()
            );
    }
}

Include the CSRF Token

In order for the synchronizer token pattern to protect against CSRF attacks, we must include the actual CSRF token in the HTTP request. This must be included in a part of the request (i.e. form parameter, HTTP header, etc) that is not automatically included in the HTTP request by the browser.

Spring Security’s CsrfFilter exposes a CsrfToken as an HttpServletRequest attribute named _csrf. This means that any view technology can access the CsrfToken to expose the expected token as either a form or meta tag. Fortunately, there are integrations listed below that make including the token in form and ajax requests even easier.

Form URL Encoded

In order to post an HTML form the CSRF token must be included in the form as a hidden input. For example, the rendered HTML might look like:

Example 14.5. CSRF Token HTML

<input type="hidden"
    name="_csrf"
    value="4bfd1575-3ad1-4d21-96c7-4ef2d9f86721"/>

Next we will discuss various ways of including the CSRF token in a form as a hidden input.

Automatic CSRF Token Inclusion

Spring Security’s CSRF support provides integration with Spring’s RequestDataValueProcessor via its CsrfRequestDataValueProcessor. This means that if you leverage Spring’s form tag library, Thymleaf, or any other view technology that integrates with RequestDataValueProcessor, then forms that have an unsafe HTTP method (i.e. post) will automatically include the actual CSRF token.

csrfInput Tag

If you are using JSPs, then you can use Spring’s form tag library. However, if that is not an option, you can also easily include the token with the csrfInput tag.

CsrfToken Request Attribute

If the other options for including the actual CSRF token in the request do not work, you can take advantage of the fact that the CsrfToken is exposed as an HttpServletRequest attribute named _csrf.

An example of doing this with a JSP is shown below:

Example 14.6. CSRF Token in Form with Request Attribute

<c:url var="logoutUrl" value="/logout"/>
<form action="${logoutUrl}"
    method="post">
<input type="submit"
    value="Log out" />
<input type="hidden"
    name="${_csrf.parameterName}"
    value="${_csrf.token}"/>
</form>

Ajax and JSON Requests

If you are using JSON, then it is not possible to submit the CSRF token within an HTTP parameter. Instead you can submit the token within a HTTP header.

In the following sections we will discuss various ways of including the CSRF token as an HTTP request header in JavaScript based applications.

Automatic Inclusion

Spring Security can easily be configured to store the expected CSRF token in a cookie. By storing the expected CSRF in a cookie, JavaScript frameworks like AngularJS will automatically include the actual CSRF token in the HTTP request headers.

Meta tags

An alternative pattern to exposing the CSRF in a cookie is to include the CSRF token within your meta tags. The HTML might look something like this:

Example 14.7. CSRF meta tag HTML

<html>
<head>
    <meta name="_csrf" content="4bfd1575-3ad1-4d21-96c7-4ef2d9f86721"/>
    <meta name="_csrf_header" content="X-CSRF-TOKEN"/>
    <!-- ... -->
</head>
<!-- ... -->

Once the meta tags contained the CSRF token, the JavaScript code would read the meta tags and include the CSRF token as a header. If you were using jQuery, this could be done with the following:

Example 14.8. AJAX send CSRF Token

$(function () {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function(e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
});

csrfMeta tag

If you are using JSPs a simple way to write the CSRF token to the meta tags is by leveraging the csrfMeta tag.

CsrfToken Request Attribute

If the other options for including the actual CSRF token in the request do not work, you can take advantage of the fact that the CsrfToken is exposed as an HttpServletRequest attribute named _csrf. An example of doing this with a JSP is shown below:

Example 14.9. CSRF meta tag JSP

<html>
<head>
    <meta name="_csrf" content="${_csrf.token}"/>
    <!-- default header name is X-CSRF-TOKEN -->
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    <!-- ... -->
</head>
<!-- ... -->

14.1.2 CSRF Considerations

There are a few special considerations to consider when implementing protection against CSRF attacks. This section discusses those considerations as it pertains to servlet environments. Refer to the section called “CSRF Considerations” for a more general discussion.

Logging In

It is important to require CSRF for log in requests to protect against forging log in attempts. Spring Security’s servlet support does this out of the box.

Logging Out

It is important to require CSRF for log out requests to protect against forging log out attempts. If CSRF protection is enabled (default), Spring Security’s LogoutFilter to only process HTTP POST. This ensures that log out requires a CSRF token and that a malicious user cannot forcibly log out your users.

The easiest approach is to use a form to log out. If you really want a link, you can use JavaScript to have the link perform a POST (i.e. maybe on a hidden form). For browsers with JavaScript that is disabled, you can optionally have the link take the user to a log out confirmation page that will perform the POST.

If you really want to use HTTP GET with logout you can do so, but remember this is generally not recommended. For example, the following Java Configuration will perform logout with the URL /logout is requested with any HTTP method:

Example 14.10. Log out with HTTP GET

@EnableWebSecurity
public class WebSecurityConfig extends
        WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) {
        http
            .logout(logout ->
                logout
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            );
    }
}

CSRF and Session Timeouts

By default Spring Security stores the CSRF token in the HttpSession. This can lead to a situation where the session expires which means there is not an expected CSRF token to validate against.

We’ve already discussed general solutions to session timeouts. This section discusses the specifics of CSRF timeouts as it pertains to the servlet support.

It is simple to change storage of the expected CSRF token to be in a cookie. For details, refer to the the section called “Custom CsrfTokenRepository” section.

If a token does expire, you might want to customize how it is handled by specifying a custom AccessDeniedHandler. The custom AccessDeniedHandler can process the InvalidCsrfTokenException any way you like. For an example of how to customize the AccessDeniedHandler refer to the provided links for both xml and Java configuration.

Multipart (file upload)

We have already discussed how protecting multipart requests (file uploads) from CSRF attacks causes a chicken and the egg problem. This section discusses how to implement placing the CSRF token in the body and url within a servlet application.

[Note]Note

More information about using multipart forms with Spring can be found within the 1.1.11. Multipart Resolver section of the Spring reference and the MultipartFilter javadoc.

Place CSRF Token in the Body

We have already discussed the tradeoffs of placing the CSRF token in the body. In this section we will discuss how to configure Spring Security to read the CSRF from the body.

In order to read the CSRF token from the body, the MultipartFilter is specified before the Spring Security filter. Specifying the MultipartFilter before the Spring Security filter means that there is no authorization for invoking the MultipartFilter which means anyone can place temporary files on your server. However, only authorized users will be able to submit a File that is processed by your application. In general, this is the recommended approach because the temporary file upload should have a negligible impact on most servers.

To ensure MultipartFilter is specified before the Spring Security filter with java configuration, users can override beforeSpringSecurityFilterChain as shown below:

Example 14.11. Initializer MultipartFilter

public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

    @Override
    protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
        insertFilters(servletContext, new MultipartFilter());
    }
}

To ensure MultipartFilter is specified before the Spring Security filter with XML configuration, users can ensure the <filter-mapping> element of the MultipartFilter is placed before the springSecurityFilterChain within the web.xml as shown below:

Example 14.12. web.xml - MultipartFilter

<filter>
    <filter-name>MultipartFilter</filter-name>
    <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>MultipartFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Include CSRF Token in URL

If allowing unauthorized users to upload temporary files is not acceptable, an alternative is to place the MultipartFilter after the Spring Security filter and include the CSRF as a query parameter in the action attribute of the form. Since the CsrfToken is exposed as an HttpServletRequest request attribute, we can use that to create an action with the CSRF token in it. An example with a jsp is shown below

Example 14.13. CSRF Token in Action

<form method="post"
    action="./upload?${_csrf.parameterName}=${_csrf.token}"
    enctype="multipart/form-data">

HiddenHttpMethodFilter

We have already discussed the trade-offs of placing the CSRF token in the body.

In Spring’s Servlet support, overriding the HTTP method is done using HiddenHttpMethodFilter. More information can be found in HTTP Method Conversion section of the reference documentation.

14.2 Security HTTP Response 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.

14.2.1 Default Security Headers

Spring Security provides a 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 X-Frame-Options.

You can easily do this with the following Java Configuration:

Example 14.14. Customize Default Security Headers with Java Configuration

@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:

Example 14.15. Customize Default Security Headers with XML Configuration

<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 Cache Control.

@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 Cache Control.

<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:

@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:

<http>
    <!-- ... -->

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

14.2.2 Cache Control

Spring Security includes Cache Control headers by default.

However, if you actually want to cache specific responses, your application can selectively invoke 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 Static Resources portion of the Spring Reference documentation

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

Example 14.16. Cache Control Disabled with Java Configuration

@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 <cache-control> element to disable it:

Example 14.17. Cache Control Disabled with XML

<http>
    <!-- ... -->

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

14.2.3 Content Type Options

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

Example 14.18. Content Type Options Disabled with Java Configuration

@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 <content-type-options> element to disable it:

Example 14.19. Content Type Options Disabled with XML

<http>
    <!-- ... -->

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

14.2.4 HTTP Strict Transport Security (HSTS)

Spring Security provides the 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:

Example 14.20. Strict Transport Security with Java Configuration

@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 <hsts> element as shown below:

Example 14.21. Strict Transport Security with XML Configuration

<http>
    <!-- ... -->

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

14.2.5 HTTP Public Key Pinning (HPKP)

For passivity reasons, Spring Security provides servlet support for HTTP Public Key Pinning but it is no longer recommended.

You can enable HPKP headers with Java Configuration:

Example 14.22. HTTP Public Key Pinning with Java Configuration

@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 <hpkp> element as shown below:

Example 14.23. HTTP Public Key Pinning with XML Configuration

<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>

14.2.6 X-Frame-Options

By default, Spring Security disables rendering within an iframe using X-Frame-Options.

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

Example 14.24. X-Frame-Options: SAMEORIGIN with Java Configuration

@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 frame-options element within XML configuration:

Example 14.25. X-Frame-Options: SAMEORIGIN with XML Configuration

<http>
    <!-- ... -->

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

14.2.7 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:

Example 14.26. X-XSS-Protection Customization with Java Configuration

@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:

Example 14.27. X-XSS-Protection Customization with XML Configuration

<http>
    <!-- ... -->

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

14.2.8 Content Security Policy (CSP)

Spring Security does not add 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:

Example 14.28. Content Security Policy Example

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:

Example 14.29. Content Security Policy Java Configuration

@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 <content-security-policy> element as shown below:

Example 14.30. Content Security Policy Java Configuration

<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:

Example 14.31. Content Security Policy Report Only Java Configuration

@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:

Example 14.32. Content Security Policy XML Configuration

<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>

14.2.9 Referrer Policy

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

Example 14.33. Referrer Policy Java Configuration

@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 <referrer-policy> element as shown below:

Example 14.34. Referrer Policy XML Configuration

<http>
    <!-- ... -->

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

14.2.10 Feature Policy

Spring Security does not add Feature Policy headers by default. The following Feature-Policy header:

Example 14.35. Feature-Policy Example

Feature-Policy: geolocation 'self'

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

Example 14.36. Feature-Policy Java Configuration

@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 <feature-policy> element as shown below:

Example 14.37. Feature-Policy XML Configuration

<http>
    <!-- ... -->

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

14.2.11 Clear Site Data

Spring Security does not add Clear-Site-Data headers by default. The following Clear-Site-Data header:

Example 14.38. Clear-Site-Data Example

Clear-Site-Data: "cache", "cookies"

can be sent on log out with the following configuration:

Example 14.39. Clear-Site-Data Java Configuration

@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

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

14.2.12 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.

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:

X-Custom-Security-Header: header-value

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

Example 14.40. StaticHeadersWriter Java Configuration

@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 <header> element as shown below:

Example 14.41. StaticHeadersWriter XML Configuration

<http>
    <!-- ... -->

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

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 Section 14.2.6, “X-Frame-Options” it could be done with the following Java Configuration:

Example 14.42. Headers Writer Java Configuration

@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 ref attribute for XML based configuration:

Example 14.43. Headers Writer XML Configuration

<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"/>

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:

Example 14.44. DelegatingRequestMatcherHeaderWriter Java Configuration

@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:

Example 14.45. DelegatingRequestMatcherHeaderWriter XML Configuration

<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>

14.3 HTTP

All HTTP based communication should be protected using TLS.

Below you can find details around Servlet specific features that assist with HTTPS usage.

14.3.1 Redirect to HTTPS

If a client makes a request using HTTP rather than HTTPS, Spring Security can be configured to redirect to HTTPS.

For example, the following Java configuration will redirect any HTTP requests to HTTPS:

Example 14.46. Redirect to HTTPS with Java Configuration

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends
        WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) {
        http
            // ...
            .requiresChannel(channel ->
                channel
                    .anyRequest().requiresSecure()
            );
    }
}

The following XML configuration will redirect all HTTP requests to HTTPS

Example 14.47. Redirect to HTTPS with XML Configuration

<http>
    <intercept-url pattern="/**" access="ROLE_USER" requires-channel="https"/>
...
</http>

14.3.2 Strict Transport Security

Spring Security provides support for Strict Transport Security and enables it by default.

14.3.3 Proxy Server Configuration

Spring Security integrates with proxy servers.