問題
當程式有設定 CSP(Content Security Policy),值為default-src 'self';
後,
會發現 SwaggerUI index.html
會一片白白的,
Browser 主控台就會顯示CSP
的錯誤,如下,
Refused to apply inline style because it violates the following Content Security Policy directive: “default-src ‘self’”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-wkAU1AW/h8YFx0XlzvpTllAKnFEO2tw8aKErs5a26LY=’), or a nonce (‘nonce-…’) is required to enable inline execution. Note also that ‘style-src’ was not explicitly set, so ‘default-src’ is used as a fallback.
Refused to execute inline script because it violates the following Content Security Policy directive: “default-src ‘self’”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-Tui7QoFlnLXkJCSl1/JvEZdIXTmBttnWNxzJpXomQjg=’), or a nonce (‘nonce-…’) is required to enable inline execution. Note also that ‘script-src’ was not explicitly set, so ‘default-src’ is used as a fallback.
解法
因為 SwaggerUI 有使用inline style及inline script,
所以被CSP的設定擋掉了。
解法 1(加入 unsafe-inline)
所以在CSP中可以加入'unsafe-inline'
及 image 的設定(img-src data: https:;
),如下,default-src 'self';style-src 'self' 'unsafe-inline';script-src 'self' 'unsafe-inline';img-src data: https:;
解法 2(使用 nonce)
如果不想使用'unsafe-inline'
, 那就需要使用nonce
。
可以在appsettings.json
中設定 CSP 的值及要使用的nonce
,
將'unsafe-inline'
改以 'nonce-{nonceValue}'
替代,如下,
1 | { |
然後設定CSP,nonce
的值,如下,
1 | var cspNonce = _configuration["CSP:Nonce"]; |
再參考How to lock down your CSP when using Swashbuckle,
在 SwaggerUI 產生 index.html 時,將 inline script, style ,加上noce的值,如下,
1 | app.UseSwaggerUI(options => |
參考資源
How to lock down your CSP when using Swashbuckle
一時花,二時雨: 喻人做事沒有恆心,毫無決斷力,有時好時壞。