I am trying to add content security policy header in response header for all
requests. So I have created OWIN middleware
public class SecurityHeaderMiddleware
{
private readonly INonceService _nonceService = null;
private readonly Func<Task> _next;
public SecurityHeaderMiddleware(Func<Task> next, INonceService nonceService)
{
_nonceService = nonceService;
_next = next;
}
public async Task Invoke(IOwinContext context)
{
// do something here to add CSP header in context.Response.Headers
await _next.Invoke();
}
Then to invoke my middleware for each request, I register my middleware in startup.cs before PostResolveCache
stage marker as per the suggestion here
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use((context, next) =>
{
var nonceService = ServiceLocator.Current.GetInstance<INonceService>();
var middleware = new SecurityHeaderMiddleware(next, nonceService);
return middleware.Invoke(context);
});
app.UseStageMarker(PipelineStage.PostResolveCache);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
// set options here
});
MvcHandler.DisableMvcResponseHeader = true;
}
}
However, my middleware only gets invoked for actual page or any ajax request, it does not get invoked when browser make request to javascript, CSS or images
How do I invoke custom middleware for all requests? If not OWIN middleware then what are my options to add header for all requests in asp.net