Picture of the author

GAURAV VARMA


Rails 5.2 brings built-in support for defining Content Security Policies (CSP) using a clear and expressive Ruby DSL. CSP is a browser feature that restricts which resources (scripts, styles, etc.) can be loaded on your site.

Defining a policy

You can define a policy in app/controllers/application_controller.rb:

1class ApplicationController < ActionController::Base
2  content_security_policy do |p|
3    p.default_src :self, :https
4    p.font_src    :self, :https, :data
5    p.img_src     :self, :https, :data
6    p.object_src  :none
7    p.script_src  :self, :https
8    p.style_src   :self, :https
9  end
10end

Benefits of CSP

  • Mitigates XSS and injection attacks
  • Restricts third-party resource loading
  • Helps enforce secure coding practices

Links

Summary

With its new CSP DSL, Rails 5.2 allows developers to easily define and enforce strong content security policies, improving browser-side security without relying on middleware or external gems.