[Solved] V13 how to add security headers?
# help-with-umbraco
c
In previous versions I would have added the following to startup.cs:-
Copy code
// Security Additions
            app.UseHttpsRedirection();
            
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }else
            {
                app.UseHsts();
            }
            
            app.Use(async (context, next) =>
            {
              context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
              context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
              context.Response.Headers.Add("X-Xss-Protection", "1; mode=block");
              await next();
            });
As we now just have program.cs, what is the new equivalent? The docs give you code snippets but don't tell you where to put them. I guess they assume we're all dotnet 8 C# 12 Ninjas, which I'm not 😉 Any advice appreciated. Thanks.
d
Hi Craig! Inside Program.cs you should have some lines similar to this:
Copy code
WebApplication app = builder.Build();

await app.BootUmbracoAsync();
You should be able to paste your snippet behind there
c
You can do it using middleware like this:
Copy code
cs
using MyProject.Middleware;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.CreateUmbracoBuilder()
    .AddBackOffice()
    .AddWebsite()
    .AddDeliveryApi()
    .AddComposers()
    .Build();

WebApplication app = builder.Build();

await app.BootUmbracoAsync();

//here
app.UseMiddleware<SecurityHeadersMiddleware>();
//here

app.UseUmbraco()
    .WithMiddleware(u =>
    {
        u.UseBackOffice();
        u.UseWebsite();
    })
    .WithEndpoints(u =>
    {
        u.UseInstallerEndpoints();
        u.UseBackOfficeEndpoints();
        u.UseWebsiteEndpoints();
    });

await app.RunAsync();
And this is your class
Copy code
cs
namespace MyProject.Middleware;

public sealed class SecurityHeadersMiddleware
{
    private readonly RequestDelegate _next;

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

    public Task Invoke(HttpContext context)
    {
        context.Response.Headers.Add("referrer-policy", "no-referrer");

        return _next(context);
    }
}
i prefer to move it out of the program.cs file
Did that work for you @Craig100 ?
c
Thanks, sorry, haven't had a chance yet. That's on my own site, which is why I don't mind that it's currently offline again! Client stuff cropped up, lol But I will give it a go before Xmas 🙂
c
No problem. I wrote a quick blog post which has some of the other headers in it too so other people can use it for reference (aka future me) https://codeshare.co.uk/blog/how-to-add-security-headers-to-your-umbraco-13-website/
c
"Wasn't used to", I hadn't even seen it before yesterday, lol Nice article though. Thanks 🙂
19 Views