Contents
How do I generate a CSP hash?
How do you generate the hash? The easiest way to generate it is to just open the developer tools console and it will output what the expected hash of your script was in the console error message. You can also use tools such as openssl to generate it, whitespace is not ignored.
How can inline javascript be used when CSP is enabled?
When you enable CSP, it will block inline scripts, but there are some ways that you can allow inline scripts and still use Content Security Policy.
- Inline Scripts are Blocked by Default with Content Security Policy.
- Allow Inline Scripts using a Nonce.
- Allow Inline Scripts using a Hash.
- Other methods.
What are inline scripts?
When a script tag is used in the HTML file, it is called inlining. This means no external JS file is used instead javascript is put into an HTML file. Modern code has moved from manual coding and customized structures to templates that provide a framework for effective code creation processes.
What can a hash be used for in CSP?
A hash of a script or style can be used to allow it . Using a hash is one way to allow the execution of inline scripts in a Content Security Policy (CSP). Here’s how one might use it with the CSP with JavaScript:
How to allow inline scripts in CSP reference?
Assuming our nonce value is r@nd0m (you need to randomly generate a new nonce for every HTTP request), we can now use an inline script tag like this: A second approach to allow inline scripts is to use a hash, with this approach you compute the hash of your JavaScript code, and put the value in our CSP policy:
Is the hash source list directive in CSP Level 2?
The hash source list directive was added to CSP Level 2. This means that support has existed since 2015 in Chrome and Firefox, Safari 10+ or Edge 15+. It is not supported at all in Internet Explorer, you need to use the Edge browser instead. Want to learn the ins and outs CSP?
What’s the easiest way to generate a hash?
The easiest way to generate it is to just open the developer tools console and it will output what the expected hash of your script was in the console error message. You can also use tools such as openssl to generate it, whitespace is not ignored. Here is an example using openssl, which will be installed by default on most mac or linux systems: