Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Security Headers to ASP.NET Core 3.1 Web Api

I am in need to add some security headers to my new ASP.NET Core 3.1 Web API. In MVC and webform I used to do with below codes in web.config file:

<httpProtocol>
      <customHeaders>
        <add name="Strict-Transport-Security" value="max-age=31536000"/>
        <add name="X-Content-Type-Options" value="nosniff"/>
        <add name="X-Xss-Protection" value="1; mode=block"/>
        <add name="X-Frame-Options" value="SAMEORIGIN"/>
        <add name="Content-Security-Policy" value="default-src https:; img-src * 'self' data: https:; style-src 'self' 'unsafe-inline' www.google.com platform.twitter.com cdn.syndication.twimg.com fonts.googleapis.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' www.google.com cse.google.com cdn.syndication.twimg.com platform.twitter.com platform.instagram.com www.instagram.com cdn1.developermedia.com cdn2.developermedia.com apis.google.com www.googletagservices.com adservice.google.com securepubads.g.doubleclick.net ajax.aspnetcdn.com ssl.google-analytics.com az416426.vo.msecnd.net/;"/>
        <add name="Referrer-Policy" value="no-referrer-when-downgrade"/>
        <add name="Feature-Policy" value="geolocation 'none';midi 'none';notifications 'none';push 'none';sync-xhr 'none';microphone 'none';camera 'none';magnetometer 'none';gyroscope 'none';speaker 'self';vibrate 'none';fullscreen 'self';payment 'none';"/>
        <remove name="X-Powered-By" />
        <remove name="X-AspNet-Version" />
        <remove name="Server" />
      </customHeaders>
</httpProtocol>

I know we can have a web.config file in .NET Core too but I want to achieve this by adding custom codes in startup class. I have found few articles using some NUGET packages but it would be awesome if someone can give me a clear picture to add security headers in .Net Core. Thanks in advance.

like image 642
Keshab Avatar asked Nov 23 '25 03:11

Keshab


1 Answers

Create a middleware class CustomResponseHeaderMiddleware like this in your code:

public class CustomResponseHeaderMiddleware
{
    private readonly RequestDelegate _next;

    public CustomResponseHeaderMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        //To add Headers AFTER everything you need to do this
        context.Response.OnStarting(state =>
        {
            var httpContext = (HttpContext)state;
            httpContext.Response.Headers.Add("Strict-Transport-Security", "max-age=31536000");
            httpContext.Response.Headers.Add("X-Content-Type-Options", "nosniff");
            httpContext.Response.Headers.Add("X-Xss-Protection", "1; mode=block");
            httpContext.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
            //... and so on
            return Task.CompletedTask;
        }, context);

        await _next(context);
    }
}

And register this middleware in startup.cs file

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // ....
    app.UseMiddleware(typeof(CustomResponseHeaderMiddleware));
    
    app.UseMvc();
}
like image 54
Ankush Jain Avatar answered Nov 25 '25 17:11

Ankush Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!