Add Authentication to Static Files in ASP.NET Core

Published on

Setting up static files in ASP.NET Core or ASP.NET 5 is super easy. With the standard templates, all files inside the wwwroot folder are shared by default.

That's great in most cases, however there's times when you need to authenticate the user before you allow access to static resources, for example on a static site.

Here's a quick tutorial for setting up static file authentication in ASP.NET Core and ASP.NET 5.

The Code

All of the code in this tutorial should be placed inside the Configure method located inside your Startup.cs file.

Make sure that you place app.UseAuthentication(); before app.UseStaticFiles();

    app.UseAuthentication();

    app.UseStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = ctx =>
        {
            if (ctx.Context.Request.Path.StartsWithSegments("/wwwrootauth"))
            {
                ctx.Context.Response.Headers.Add("Cache-Control", "no-store")
                if (!ctx.Context.User.Identity.IsAuthenticated)
                {
                    ctx.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    ctx.Context.Response.ContentLength = 0;
                    ctx.Context.Response.Body = Stream.Null
                }
            }
        }
    });

This example assumes that you have a folder at the root of the project named wwwrootauth.

We specify via a HTTP header that files should not be cached, and any unauthorized access should result in a 401 response code.


Article Categories: # asp.net # .net # c# # identity
Date Published: Aug 1, 2020

About

A tech blog by Andy P. I talk about coding, enterprise software development, tech, games design & other things that interest me.

Signup To The Newsletter

I try to post a new interesting article every saturday.

IT Asset Management

Our friends at AssetPad are building a complete online solution for managing the IT assets within your organisation. With barcodes and documentation tools.