Silver Light and Blue Sky

C# and Infrastructure. Code is everything.

Static file authorization in ASP.NET Core MVC

When we want to serve static file ins ASP.NET Core, we should have to read this document.

Working with Static Files | Microsoft Docs

Let's imagine serving some static protected files with authorization. These files are only accessible by authorized users.

Configure Authorization

It's required to configure authorization, but it's independent of configuring static file authorization. You can configure authorization with your favorite way. Please read the document. Here is a sample.

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseIdentity();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
Locate protected files

In the above code, files under wwwroot folder can be publicly accessible as I call UseStaticFiles method. We should have to locate protected files the folder except for wwwroot folder. I create www folder and locate a file.

f:id:tanaka733:20170109122226p:plain

Serve static files with authorization

We don't have to configure service for this www folder like UseStaticFiles method. If we configure www folder for static file middleware by calling UseStaticFiles method, files under www folder can be publicly accessible. Please note all files are publicly accessible when we use Static File middleware. We only have to return FileResult in the controller action.

[Authorize]
public IActionResult File()
{
    return PhysicalFile(Path.Combine(environment.ContentRootPath, "www", "banner1.svg"), "image/svg+xml");
}

We should have to return PhysicalFileResult by specifying an absolute file path. Then we can serve banner1.svg file with authorization.

f:id:tanaka733:20170109123353p:plain