ASP Net Core Apply middleware inside UseSpa middleware

694 Views Asked by At

I'm trying to include security headers on static files response using Asp Net Core. As I'm using a Single Page Application, I need to include that headers inside the UseSpa method.

What I am doing:

app.UseWhen(x => !x.Request.Path.Value.StartsWith("/api"), builder =>
{
    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions()
        {
            OnPrepareResponse = ctx => {
                            
                var headers = ctx.Context.Response.GetTypedHeaders();
                headers.CacheControl = new CacheControlHeaderValue
                {
                    Public = true,
                    MaxAge = TimeSpan.FromDays(0)
                };

            }
        };

        if (env.IsDevelopment())
        {
            spa.UseReactDevelopmentServer(npmScript: "start");
        }
    });
});

Using NWebSec package, I want to execute the Csp middleware inside th useSpa method.

app.UseWhen(x => !x.Request.Path.Value.StartsWith("/api"), builder =>
{
    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions()
        {
            OnPrepareResponse = ctx => {
                            
                var headers = ctx.Context.Response.GetTypedHeaders();
                headers.CacheControl = new CacheControlHeaderValue
                {
                    Public = true,
                    MaxAge = TimeSpan.FromDays(0)
                };

                var appBuilder = //somehow get the appbuilder
                appBuilder.UseCsp(options => ...);
            }
        };

        if (env.IsDevelopment())
        {
            spa.UseReactDevelopmentServer(npmScript: "start");
        }
    });
});
0

There are 0 best solutions below