§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.
§Enabling the security headers filter
To enable the security headers filter, add the Play filters project to your libraryDependencies
in build.sbt
:
libraryDependencies += filters
Now add the security headers filter to your filters, which is typically done by creating a Filters
class in the root of your project:
- Scala
-
import javax.inject.Inject import play.api.http.HttpFilters import play.filters.headers.SecurityHeadersFilter class Filters @Inject() (securityHeadersFilter: SecurityHeadersFilter) extends HttpFilters { def filters = Seq(securityHeadersFilter) }
- Java
-
import play.api.mvc.EssentialFilter; import play.filters.headers.SecurityHeadersFilter; import play.http.HttpFilters; import javax.inject.Inject; public class Filters implements HttpFilters { @Inject SecurityHeadersFilter securityHeadersFilter; public EssentialFilter[] filters() { return new EssentialFilter[] { securityHeadersFilter }; } }
The Filters
class can either be in the root package, or if it has another name or is in another package, needs to be configured using play.http.filters
in application.conf
:
play.http.filters = "filters.MyFilters"
§Configuring the security headers
Scaladoc is available in the play.filters.headers package.
The filter will set headers in the HTTP response automatically. The settings can can be configured through the following settings in application.conf
play.filters.headers.frameOptions
- sets X-Frame-Options, “DENY” by default.play.filters.headers.xssProtection
- sets X-XSS-Protection, “1; mode=block” by default.play.filters.headers.contentTypeOptions
- sets X-Content-Type-Options, “nosniff” by default.play.filters.headers.permittedCrossDomainPolicies
- sets X-Permitted-Cross-Domain-Policies, “master-only” by default.play.filters.headers.contentSecurityPolicy
- sets Content-Security-Policy, “default-src ‘self’” by default.
Any of the headers can be disabled by setting a configuration value of null
, for example:
play.filters.headers.frameOptions = null
For a full listing of configuration options, see the Play filters reference.conf
.
Next: Configuring CORS