Integrity
explaination
This demo page is to help you understand integrity attribute.
You should be able to use querystring to control whether integrity is correct.
- wrong-integrity=all to set integrity incorrectly for all resources
- wrong-integrity=script to set integrity incorrectly for script
- wrong-integrity=style to set integrity incorrectly for style
- wrong-integrity=invalid to set invalid integrity
Available hash algorithms are sha256, sha384 and sha512. One or more hashes can be used as integrity attribute. The hash should have one of sha256-, sha384- or sha512- at front and should be joined by white space.
When multiple hash results are provided, the strongest hash result will be used. If multiple hash results exists with same hash algorithm, the resource will be considered as valid if any of the hashes matches the actual one. More examples regarding multiple hashes in integrity can be found in this demo.
Following is the Node.js code you can use to generate hash for given content.
require('crypto')
.createHash(type) // 'sha256', 'sha384' or 'sha512'
.update(content, 'utf8')
.digest('base64');
Status of resources loading
- Style failed to load
- Style loaded successfully
- Script failed to load
Crossorigin
When using SRI, it is usually necessary to include crossorigin="anonymous" as well. The reason behind this is, SRI is designed to validate resources on third-party CDN, where security is out of our hand. That means, the request is cross-domain. To ensure the browser can read the content and calculate hash, crossorigin="anonymous" is required and CDN must explicitly allow this. Otherwise the load of content will fail.
For resources within same domain, crossorign="anonymous" isn't required. However, SRI does not play a key role in such scenario as well.