Swagger UI includes an inline-script
which makes it more difficult to enforce the Content-Security-Policy
header.
This Gist shows a way to add an exception for Swagger UI in order to be able to enforce
the policy to an effectiv level. This is useful for example in FastAPI
where Swagger UI is added automatically for API documentation.
"default-src 'self'; script-src 'self' https://cdn.jsdelivr.net/npm/swagger-ui-dist@<version>/swagger-ui-bundle.js 'sha256-<inline-script sha256>'; style-src 'self' https://cdn.jsdelivr.net/npm/swagger-ui-dist@<version>/swagger-ui.css; frame-ancestors 'none'"
The script above shows an example for a Content-Security-Policy
header.
The dependencies (https://cdn.jsdelivr.net/npm/swagger-ui-dist
) are fairly simple as only required the URL.
Both URLs (script and css) contain a version placeholder that must be adapted to the used version of Swagger UI.
If you don't know the version, add the header, leave the placeholder, start your server and look into the browser console.
Displaying Swagger UI will be blocked due to this policy and it will specify for which URLs (containing the version) the retrieval was blocked.
-
Inspect your Swagger UI based API documentation in the browser.
-
Inside the
<body>
, you will find the<script>
section. -
Copy the entire content of the
<script>
section without the tags. -
Use the following command (Linux, MacOS) to create a base64 encoded sha256 hash from the script. Instead of
"$(pbpaste)"
you can also insert the script directly. However, since the hash depends on every character and space, it can quickly result in invalid hashes.echo -n "$(pbpaste)" | openssl sha256 -binary | openssl base64
-
Use the base64 hash in the header above (e.g.
'sh256-<insert here>'
)
After restarting the server, you should be able to see Swagger UI again 🎉