其他分享
首页 > 其他分享> > 2021-03-20

2021-03-20

作者:互联网

Turbolinks broken by default with a secure CSP

Good: Rails includes built-in tools to generate a CSP

Great: That CSP encourages disallowing unsafe evaluation of inline JS

Incredible: Rails includes javascript_tag(nonce: true) helper so you can include nonced inline JS

WTF If you use all these tools together with Turbolinks none of the nonces work.

If you want UJS, Turbolinks, and other inline nonced JS to work you need to do the following:

1.Change Nonce generation so that nonces do not change for turbolinks requests (as the DOM is not updated)

# In config/initializers/content_security_policy.rb
Rails.application.config.content_security_policy_nonce_generator = -> (request) do
  # use the same csp nonce for turbolinks requests
  if request.env['HTTP_TURBOLINKS_REFERRER'].present?
    request.env['HTTP_X_TURBOLINKS_NONCE']
  else
    SecureRandom.base64(16)
  end

2.Inject a header into turbolinks requests so the above nonce generation code works

// Somewhere in /app/javascript
document.addEventListener("turbolinks:request-start", function(event) {
  var xhr = event.data.xhr;
  xhr.setRequestHeader("X-Turbolinks-Nonce", $("meta[name='csp-nonce']").prop('content'));
});

3.Because nonces can only be accessed via their IDL attribute after the page loads (for security reasons), they need to be read via JS and added back as normal attributes in the DOM before the page is cached otherwise on cache restoration visits, the nonces won’t be there!

// Somewhere in /app/javascript
document.addEventListener("turbolinks:before-cache", function() {
  $('script[nonce]').each(function(index, element) {
    $(element).attr('nonce', element.nonce)
  })
})

标签:nonce,03,20,turbolinks,request,JS,2021,nonces,Turbolinks
来源: https://blog.csdn.net/qq_43565746/article/details/115035090