namespace XSSDefenses.XSSDefenses.MiddlerWare { public sealed class CspOptionMiddlerWare { private const string HEADER = "Content-Security-Policy"; private readonly RequestDelegate next; private readonly CspOptions options; public CspOptionMiddlerWare( RequestDelegate next, CspOptions options) { this.next = next; this.options = options; } public async Task Invoke(HttpContext context) { context.Response.Headers.Add(HEADER, GetHeaderValue()); await this.next(context); } private string GetHeaderValue() { var value = ""; value += GetDirective("default-src", this.options.Defaults); value += GetDirective("script-src", this.options.Scripts); value += GetDirective("style-src", this.options.Styles); value += GetDirective("img-src", this.options.Images); value += GetDirective("font-src", this.options.Fonts); value += GetDirective("media-src", this.options.Media); return value; } private string GetDirective(string directive, List<string> sources) => sources.Count > 0 ? $"{directive} {string.Join(" ", sources)}; " : ""; } }
以及设置它的扩展方法。
namespace XSSDefenses.XSSDefenses.Extensions { public static class CspMiddlewareExtensions { public static IApplicationBuilder UseCsp( this IApplicationBuilder app, Action<CspOptionsBuilder> builder) { var newBuilder = new CspOptionsBuilder(); builder(newBuilder); var options = newBuilder.Build(); return app.UseMiddleware<CspOptionMiddlerWare>(options); } } }
我们现在可以在Startup类中配置中间件。
app.UseCsp(builder => { builder.Styles.AllowSelf() .Allow(@"https://ajax.aspnetcdn.com/"); });
启动发现,观察网络资源。浏览器已经允许本地和远程资源。