Skip to content

[Issue] Error while add header response for .NET Core WebAPI 7 #1431

Open

Description

My project using .NET Core 7.
My project needs to configure security response headers for .Net core webapi, but when adding the following response header, the api cannot call or the response returns 200 but blank data.

I run on IIS Server, Window Server 2023.

Please help me guide to me fix this issue.

image

Activity

  1. shankar-vattamwar commented on Sep 11, 2024

    @shankar-vattamwar

    Tien Nguyen (@nguyenthanhtien)
    modified code

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts(); // This enables HSTS (HTTP Strict Transport Security)
        }
    
        app.UseSwashbuckleSwagger();
        //app.UseSwaggerUI();
        app.UseHttpsRedirection();
    
        app.UseRouting();
    
        // Add Security Headers Middleware
        app.Use(async (context, next) =>
        {
            // Add security response headers
            context.Response.Headers.Add("Content-Security-Policy", "default-src 'self';");
            context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
            context.Response.Headers.Add("X-Frame-Options", "DENY");
            // Uncomment X-XSS-Protection if necessary
            // context.Response.Headers.Add("X-Xss-Protection", "1; mode=block");
            context.Response.Headers.Add("Cache-Control", "no-cache");
    
            // Allow OPTIONS requests to pass through for CORS preflight
            if (context.Request.Method != "OPTIONS")
            {
                await next(); // Proceed to the next middleware
            }
            else
            {
                // Handle preflight CORS requests
                context.Response.StatusCode = 200;
                await context.Response.CompleteAsync();
            }
        });
    
        app.UseCors("CorsPolicy");
    
        app.UseAuthentication();
        app.UseAuthorization();
    
        app.UseMiddleware<SeqLoggingMiddleware>();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    
        app.UseHealthCheckEntityFramework();
    
    }
    

    **

    Security Headers Middleware Placement: Moved just after UseRouting() and before UseCors(), UseAuthentication(), and UseAuthorization(). This ensures that security headers are applied properly before any authentication or CORS policies are checked.
    Handling of OPTIONS Requests: The middleware now handles CORS preflight (OPTIONS) requests separately to avoid unnecessary security headers being applied and blocking the response.
    Ensuring Security Headers: Added all required headers (Content-Security-Policy, X-Content-Type-Options, X-Frame-Options, Cache-Control). You can uncomment the X-Xss-Protection if needed

    Suggestion:
    Log Middleware: Add some logging around the middleware if you still encounter issues to better understand what’s happening.
    CORS Policy: Double-check that your CORS policy is allowing the necessary origins and headers if the API is consumed from another domain.

    Example middleware correct order

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
    
        app.UseHttpsRedirection();
        app.UseRouting();
    
        // Add Security Headers Middleware here
        app.Use(async (context, next) =>
        {
            context.Response.Headers.Add("Content-Security-Policy", "default-src 'self';");
            context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
            context.Response.Headers.Add("X-Frame-Options", "DENY");
            context.Response.Headers.Add("Cache-Control", "no-cache");
    
            if (context.Request.Method != "OPTIONS")
            {
                await next();
            }
            else
            {
                context.Response.StatusCode = 200;
                await context.Response.CompleteAsync();
            }
        });
    
        app.UseCors("CorsPolicy");
        app.UseAuthentication();
        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    
        app.UseMiddleware<SeqLoggingMiddleware>();
        app.UseHealthCheckEntityFramework();
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions