Our application is on Rails 5.2 and it is serving assets with webpacker without the asset pipeline. I was wondering what is the best way to set the nonce attributes on the script tag.
In content_security_policy.rb
, there is a content_security_policy_nonce_generator
for UJS, I was wondering if I can still use that without any side effect. The following work and I was just wondering what is the best practice for doing something like this.
#initializers/content_security_policy.rb
# If you are using UJS then enable automatic nonce generation
Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16)
In application.html.erb
, if I want to have nonce on the script tag, I will have to get it from the request. According here: https://api.rubyonrails.org/classes/ActionDispatch/ContentSecurityPolicy/Request.html#method-i-content_security_policy_nonce
#app/views/layouts/application.html.erb
<!DOCTYPE html>
<html dir="ltr">
<head>
<title>FruitsMarket</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_pack_tag 'application' %>
<%= javascript_pack_tag 'polyfills' %>
<%= javascript_pack_tag 'application' %>
<script type="text/javascript" nonce=<%= request.content_security_policy_nonce %>>
alert('hi');
</script>
</head>
<body>
<%= yield %>
</body>
</html>