Documentation

You are viewing the documentation for the 2.3.5 release in the 2.3.x series of releases. The latest stable release series is 3.0.x.

§Configuring Security Headers

Play provides a security headers filter that can be used to configure some default headers in the HTTP response to mitigate security issues and provide an extra level of defense for new applications.. It can be added to the applications filters using the Global object. To enable the security headers filter, add the Play filters helpers dependency to your project in build.sbt:

libraryDependencies += filters

§Enabling security headers in Scala

Scaladoc is available in the play.filters.headers package.

The simplest way to enable the SecurityHeaders filter in a Scala project is to use the WithFilters helper:

import play.api._
import play.api.mvc._
import play.filters.headers.SecurityHeadersFilter

object Global extends WithFilters(SecurityHeadersFilter()) with GlobalSettings {
  // onStart, onStop etc...
}

The filter will set headers in the HTTP response automatically. The settings can can be configured through the following settings in application.conf

NOTE: Because these are security headers, they are “secure by default.” If the filter is applied, but these fields are NOT defined in Configuration, the defaults on the filter are NOT omitted, but are instead set to the strictest possible value.

The filter can also be configured on a custom basis in code:

val filter = {
   val configuration = play.api.Play.current.configuration
   val securityHeadersConfig:DefaultSecurityHeadersConfig = new SecurityHeadersParser().parse(configuration).asInstanceOf[DefaultSecurityHeadersConfig]
   val sameOriginConfig:SecurityHeadersConfig = securityHeadersConfig.copy(frameOptions = Some("SAMEORIGIN"))
   SecurityHeadersFilter(sameOriginConfig)
}

§Enabling security headers in Java

To enable security headers in Java, add it to the list of filters in the Global object:

import play.GlobalSettings;
import play.api.mvc.EssentialFilter;
import play.filters.headers.SecurityHeadersFilter;

public class Global extends GlobalSettings {
    public <T extends EssentialFilter> Class<T>[] filters() {
        return new Class[]{SecurityHeadersFilter.class};
    }
}