Skip to main content
 首页 » 编程设计

c#之我如何使 Umbraco 与 NWebSec 的内置 CSP 报告事件处理程序配合得很好

2024年01月31日21lvdongjie

我正在使用 Umbraco CMS 版本 7 的网站上工作。我正在使用 NWebSec 在网站上实现 CSP header 。 NWebSec 内置了在违反 CSP 时引发 .Net 事件的功能。通常你会用这样的东西来捕捉那个事件:

protected void NWebSecHttpHeaderSecurityModule_CspViolationReported(object sender, CspViolationReportEventArgs e) 
    { 
        var report = e.ViolationReport; 
        var serializedReport = JsonConvert.SerializeObject(report.Details); 
 
        // Do a thing with the report 
    } 

在 Global.asax.cs 文件中。但据我所知,Umbraco 抢占了 Global.asax.cs 文件,并且它吃掉了任何抛出的事件。我有一个包含一些自定义事件处理程序的文件,例如:

public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) 

处理通常位于 Global.asax.cs 文件中的应用程序启动代码的标准片段,但将 NWebSec 事件处理程序放在同一文件中不起作用。大概是因为它使用的是 .Net 事件处理程序语法,而不是 Umbraco 替换它的任何语法。

如何访问 NWebSec 抛出的事件?

请您参考如下方法:

Global.asax 类继承自 UmbracoApplication 所以不,你不能使用它。这有很多原因,包括启用在 web 上下文之外“运行”Umbraco 的能力——即在控制台应用程序中)。

在查看 NWebSec 文档网站上的可用文档后,我认为您不能只将 NWebSecHttpHeaderSecurityModule_CspViolationReported 事件处理程序方法放在类中,您还需要将其连接起来。它应该看起来像这样:

public class MyGlobalEventHandler : ApplicationEventHandler { 
 
    protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) 
    { 
        var nWebSecHttpHeaderSecurityModule = umbracoApplication.Modules["NWebSecHttpHeaderSecurityModule"] as HttpHeaderSecurityModule; 
        if (nWebSecHttpHeaderSecurityModule != null) { 
            nWebSecHttpHeaderSecurityModule.CspViolationReported += NWebSecHttpHeaderSecurityModule_CspViolationReported; 
        } 
 
        base.ApplicationStarted(umbracoApplication, applicationContext); 
    } 
 
    protected void NWebSecHttpHeaderSecurityModule_CspViolationReported(object sender, CspViolationReportEventArgs e) 
    { 
        var report = e.ViolationReport; 
        var serializedReport = JsonConvert.SerializeObject(report.Details); 
 
        // Do a thing with the report 
    } 
} 

如果您使用支持 OWIN (7.3.0) 的较新版本的 Umbraco,您可以使用 NWebsec.Owin 库,它可能会给您带来更好的结果和更大的灵 active 。