How do I serve static files only to authorized users?

こ雲淡風輕ζ 提交于 2019-11-27 12:43:48
Clint B

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.

Guy

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

john lee

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");
                }
            }
        });

If you have a login form (Login.html), a simple solution is to redirect the user to the login page if user is not authenticated and he's requesting a protected resource (file under /protected folder). In Startup.cs, in Configure method insert this code:

app.Use(async (context, next) =>
{
    if (!context.User.Identity.IsAuthenticated && context.Request.Path.StartsWithSegments("/protected"))
    {
        context.Response.Redirect("/Login.html");
        return;
    }
    await next.Invoke();
});
Pragmatic Coder

This is a very simple example, but it can be changed to check for specific roles, and the code can be moved out of the Startup.cs for more flexibility.

app.Use(async (context, next) =>
               {
                   if (!context.User.Identity.IsAuthenticated
                       && context.Request.Path.StartsWithSegments("/excelfiles"))
                   {
                       throw new Exception("Not authenticated");
                   }
                   await next.Invoke();
               });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!