Protect certain folders in wwwroot with authetication in asp.net core mvc

1.4k views Asked by At

I have placed few folders having static content in wwwroot. For some folders i need that user is authenticated to view those.

For this i have added code in Startup like below.

app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = ctx=>
                {
if(!ctx.Context.User.Identity.IsAuthenticated && ctx.Context.Request.Path.Value("admin/manuals"))
                    {
                        ctx.Context.Response.Redirect("/");
                    }
        }
        }

Although i am authenticated but i am always getting the isAuthenticated false. Why i am getting this also..

Also what can be the better way to handle such scenario.

1

There are 1 answers

0
Rena On

Here are two ways to serve files based on authorization:

The fist way like what you did to configre the static files middleware.

Although i am authenticated but i am always getting the isAuthenticated false.

Be sure call UseStaticFiles after UseAuthorization:

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseStaticFiles();   
//...

The second way is to serve them via an action method to which authorization is applied and return a FileResult object:

[Authorize]
public IActionResult BannerImage()
{
    var filePath = Path.Combine(
        _env.ContentRootPath, "MyStaticFiles", "images", "red-rose.jpg");

    return PhysicalFile(filePath, "image/jpeg");
}

Reference:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1#static-file-authorization