crossorigin and CORS — why SRI silently switches off
integrity is only checked on a response fetched with CORS. Without the crossorigin attribute the browser fetches the file no-cors and the hash is simply ignored.
A no-cors response body cannot be read
A script tag without crossorigin issues a no-cors request. The response is opaque, so neither your JavaScript nor the browser's integrity check can read the body.
So a cross-origin file with integrity but no crossorigin appears to work: it loads without an error. It looks protected while nothing is being verified.
What crossorigin=anonymous does
The attribute switches the fetch to CORS mode. If the server allows the origin with Access-Control-Allow-Origin, the browser can read the body and compare the digest. Cookies and credentials are not sent.
For a static CDN, a single Access-Control-Allow-Origin: * is enough. Without that header even a correct hash is blocked at the CORS step.
use-credentials has more conditions
Resources that need cookies use crossorigin="use-credentials", but then the server cannot answer with Access-Control-Allow-Origin: *. It must echo the exact origin and also send Access-Control-Allow-Credentials: true.
If any condition is missing the browser blocks the response. Public CDN assets almost always want anonymous.
Why same-origin needs no attribute
Relative paths and files on the same host are not CORS requests, so integrity works without crossorigin. Adding the attribute only introduces a CORS negotiation, so leave it off for same-origin files.
Reading the console
Different symptoms, different causes.
| Console message | Cause |
|---|---|
| Failed to find a valid digest in the 'integrity' attribute | Hash mismatch, or the body was not readable over CORS |
| blocked by CORS policy: No 'Access-Control-Allow-Origin' | The server sends no ACAO header |
| 'Access-Control-Allow-Origin' header must not be '*' | use-credentials combined with a wildcard |
| Loading module … was blocked | CORS or MIME problem on a module script |
Questions
I added crossorigin and still get an integrity error.
CORS passed but the bytes differ. Check whether the deployed file changed, or the line endings or minification differ, then recompute from the final file.
Does crossorigin without integrity do anything?
Yes: it makes errors and stack traces readable. It is not integrity protection, though.
Sources
Every example here can be pasted into the workbench as it is.
Open the workbench