Module: ActionController::ContentSecurityPolicy::ClassMethods

Defined in:
actionpack/lib/action_controller/metal/content_security_policy.rb

Instance Method Summary collapse

Instance Method Details

#content_security_policy(enabled = true, **options, &block) ⇒ Object

Overrides parts of the globally configured ‘Content-Security-Policy` header:

class PostsController < ApplicationController
  content_security_policy do |policy|
    policy.base_uri "https://www.example.com"
  end
end

Options can be passed similar to ‘before_action`. For example, pass `only: :index` to override the header on the index action only:

class PostsController < ApplicationController
  content_security_policy(only: :index) do |policy|
    policy.default_src :self, :https
  end
end

Pass ‘false` to remove the `Content-Security-Policy` header:

class PostsController < ApplicationController
  content_security_policy false, only: :index
end


40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'actionpack/lib/action_controller/metal/content_security_policy.rb', line 40

def content_security_policy(enabled = true, **options, &block)
  before_action(options) do
    if block_given?
      policy = current_content_security_policy
      instance_exec(policy, &block)
      request.content_security_policy = policy
    end

    unless enabled
      request.content_security_policy = nil
    end
  end
end

#content_security_policy_report_only(report_only = true, **options) ⇒ Object

Overrides the globally configured ‘Content-Security-Policy-Report-Only` header:

class PostsController < ApplicationController
  content_security_policy_report_only only: :index
end

Pass ‘false` to remove the `Content-Security-Policy-Report-Only` header:

class PostsController < ApplicationController
  content_security_policy_report_only false, only: :index
end


66
67
68
69
70
# File 'actionpack/lib/action_controller/metal/content_security_policy.rb', line 66

def content_security_policy_report_only(report_only = true, **options)
  before_action(options) do
    request.content_security_policy_report_only = report_only
  end
end