Skip to content

Instantly share code, notes, and snippets.

@m-lukas
Created March 9, 2023 16:46
Show Gist options
  • Save m-lukas/5bbf98e0dbade2d9f9428956512bdd31 to your computer and use it in GitHub Desktop.
Save m-lukas/5bbf98e0dbade2d9f9428956512bdd31 to your computer and use it in GitHub Desktop.
Content-Security-Policy with Swagger UI (e.g. for FastAPI)

How to enable Content-Security-Policy with Swagger UI

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.

Adding the header

"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.

Adding an exception for the inline-script

  1. Inspect your Swagger UI based API documentation in the browser.

  2. Inside the <body>, you will find the <script> section.

  3. Copy the entire content of the <script> section without the tags.

  4. 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

  5. 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 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment