How do I serve static files only to authorized users?

in .net core create a dedicated directory www in same level as wwwroot, and use the following code:

public HomeController(IHostingEnvironment hostingEnvironment)
{
    _hostingEnvironment = hostingEnvironment;
}

[Authorize(Roles = "SomeRole")]
public IActionResult Performance()
{
    return PhysicalFile(Path.Combine(_hostingEnvironment.ContentRootPath,
                                     "www", "MyStaticFile.pdf"), "application/pdf");
}

Based on the following answer (for .netCore): static file authorization


Yes, they should go in wwwroot. Currently there is no built-in way to secure wwwroot directories. But creating a middleware module to accomplish it is pretty straightforward. There is an easy to follow tutorial here.

If you're not familiar with developing middleware, I posted a GitHub project that shows how to create middleware in three easy steps. You can download the project here.

You don't need a controller to access static files.


For authentication check while retrieving file:

        app.UseStaticFiles(new StaticFileOptions()
        {
            OnPrepareResponse = (context) =>
            {
                if (!context.Context.User.Identity.IsAuthenticated && context.Context.Request.Path.StartsWithSegments("/excelfiles"))
                {
                    throw new Exception("Not authenticated");
                }
            }
        });