Modifying Response Header in v8
# help-with-umbraco
p
In v8 I need to add a nonce value to the
Content-Security-Policy
currently set in the web.config. The value in the web.config is similar to the following:
Copy code
script-src 'self' 'nonce-{0}'
What I cannot seem to do is find a point in the pipeline where this header exists so that I can replace the placeholder with the server generated nonce. I have a component composer as follows:
Copy code
public class HttpApplicationEventsComposer : ComponentComposer<HttpApplicationEventsComponent> 
{}

private void UmbracoApplicationBase_ApplicationInit(object sender, System.EventArgs e)
{
    if (!(sender is HttpApplication application))
    {
        return;
    }

    var app = application;
    app.PreSendRequestHeaders += AppOnPreSendRequestHeaders;
}

private void AppOnPreSendRequestHeaders(object sender, EventArgs e)
{
    if (!HttpContext.Current.Response.Headers.AllKeys.Contains("Content-Security-Policy-Report-Only"))
    {
        return;
    }

    var cspReportOnlyHeader = HttpContext.Current.Response.Headers["Content-Security-Policy-Report-Only"];
    var scriptNonce = SecurityHelper.GenerateNonce(32); 
    
    HttpContext.Current.Response.Headers["Content-Security-Policy-Report-Only"] =
        string.Format(cspReportOnlyHeader, scriptNonce);
    HttpContext.Current.Items[Constants.Keys.ContentSecurityPolicyScriptNonce] = scriptNonce;
}
At no point can I find the header present in order to modify it before the response is returned to the client. I may well have been looking at this for too long and I am missing something obvious but I can't at the moment see how I can achieve this. Any ideas?
s
j
Oh wow I did work on that an eternity ago
p
Thanks @Sebastiaan and @Janae I will take a look into that 👍
This still does not seem to allow me to access the existing header. Stepping through the code I can see no point in pipeline where the header exists yet sure enough if I view the response headers after the request is completed I can see the header that is set by the web.config configuration.
I've had to change my approach and remove the standard CSP Header from the web.config and I am adding the header using a custom class inheriting from
IComponent
and using that to hook into the
BeginRequest
and
EndRequest
events in the request pipeline. I am however now curious if what I was trying to do is actually possible and if not, why not. If I can find some time I will try and do some research into where in the pipeline the headers are added that are defined in the
customHeaders
section of the web.config.
k
We've had to change the order of http modules (using inetmgr, I think) to achieve similar things in the past. If you look in inetmgr at the http modules actually included in the pipeline iirc there's a whole bunch you never think about. The ones referenced by web.config are only a subset, and the machine-wide web.config adds some more.