Blazor交互式服务器应用为何出现Content Policy错误?
问题修复方案
1. Worker创建失败的问题
原因:Blazor Interactive Server使用blob:协议的URL创建Worker,而你的CSPworker-src规则仅允许了域名,blob:属于特殊协议 scheme,不属于域名匹配范围,必须显式声明允许。
修复:在WorkerSources中添加"blob:":
.WorkerSources(s => s.Self() .CustomSources("blob:", "louishowe-dev.azurewebsites.net", "*.microsoft.com", "*.windows.net", "*.azurewebsites.net"))
2. 字体加载失败的问题
原因:Google字体的CSS文件来自fonts.googleapis.com,但实际字体文件托管在fonts.gstatic.com,你的font-src规则仅允许了CSS来源,未包含字体文件的实际存储域名。
修复:在FontSources中添加"fonts.gstatic.com":
.FontSources(s => s.Self() .CustomSources("fonts.googleapis.com", "fonts.gstatic.com"))
修正后的完整CSP配置
app.UseHsts(options => options.MaxAge(days: 30)); app.UseXContentTypeOptions(); app.UseXXssProtection(options => options.EnabledWithBlockMode()); app.UseXfo(options => options.SameOrigin()); app.UseReferrerPolicy(opts => opts.NoReferrerWhenDowngrade()); app.UseCsp(options => options .DefaultSources(s => s.Self() .CustomSources("data:", "https:")) .StyleSources(s => s.Self() .CustomSources("*.microsoft.com", "*.windows.net", "*.azurewebsites.net", "www.google.com", "fonts.googleapis.com") .UnsafeInline() ) .ImageSources(s => s.Self() .CustomSources("data:", "https:")) .FontSources(s => s.Self() .CustomSources("fonts.googleapis.com", "fonts.gstatic.com")) .ScriptSources(s => s.Self() .CustomSources("*.microsoft.com", "*.windows.net", "*.azurewebsites.net", "www.google.com", "cse.google.com") .UnsafeInline() .UnsafeEval() ) .WorkerSources(s => s.Self() .CustomSources("blob:", "louishowe-dev.azurewebsites.net", "*.microsoft.com", "*.windows.net", "*.azurewebsites.net")) ); // NWebSec does not handle this (no updates to that library in 4 years) app.Use(async (context, next) => { context.Response.Headers.Add("Permissions-Policy", "geolocation=*, camera=(), microphone=()"); await next.Invoke(); });
内容的提问来源于stack exchange,提问作者David Thielen
相关产品推荐
相关产品推荐

