1

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

Community
  • 1
  • 1
LP13
  • 30,567
  • 53
  • 217
  • 400

2 Answers2

0

I've noticed that owin middleware is only invoked for requests which are serviced by MVC handler.

Answer was to add catch all routing, so everything is routed to mvc handler.

Shadow
  • 2,089
  • 2
  • 23
  • 45
-1

I guess the PostAuthorize stage marker should be set to handle static content requests. It's even mentioned in the linked issue's comments:

app.Use(...);

app.UseStageMarker(PipelineStage.PostAuthorize);
Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114