Product SiteDocumentation Site

3.2.8. Configuring Rails

Enabling security related headers in Rails application is simplified by SecureHeaders gem. After installation, it automatically adds:
  • Content Security Policy
  • HTTP Strict Transport Security
  • X-Frame-Options
  • X-XSS-Protection
  • X-Content-Type-Options
After adding the gem to project's Gemfile
gem 'secure_headers'
enable its functionality by adding ensure_security_headers directive to ApplicationController:
class ApplicationController < ActionController::Base
Configuration of the header values can be done by creating an initializer and overriding default gem configuration:
::SecureHeaders::Configuration.configure do |config|
config.hsts = {:max_age => 20.years.to_i, :include_subdomains => true}
config.x_frame_options = 'DENY'
config.x_content_type_options = "nosniff"
config.x_xss_protection = {:value => 1, :mode => 'block'}
config.csp = {
  :enforce => true,
  :default_src => "https://* self",
  :frame_src => "https://* http://*",
  :img_src => "https://*",
  :report_uri => '//'
It is important to set :enforce to true in CSP configuration, because SecureHeaders defaults to false, which indicates Content-Security-Policy-Report-Only header will be sent and the policy will not be enforced, only monitored (see Section 3.2.3, “Content Security Policy (CSP)”). SecureHeaders will also set value of :default_src to all empty directives explicitly and not rely on the user agent's behaviour.