使用 asp.net core mvc 中的身份验证保护 wwwroot 中的某些文件夹

2024-05-10

我在 wwwroot 中放置了几个包含静态内容的文件夹。 对于某些文件夹,我需要用户经过身份验证才能查看这些文件夹。

为此,我在启动中添加了代码,如下所示。

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

虽然我已经过身份验证,但我总是得到 isAuthenticated false。 为什么我也收到这个..

还有什么更好的方法来处理这种情况。


以下是基于授权提供文件的两种方法:

第一种方法就像配置静态文件中间件一样。

虽然我已经过身份验证,但我总是得到 isAuthenticated false。

一定要打电话UseStaticFiles after UseAuthorization:

app.UseRouting();

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

app.UseStaticFiles();   
//...

第二种方法是通过应用授权的操作方法为它们提供服务并返回 FileResult 对象:

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

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

参考:

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 asp.net core mvc 中的身份验证保护 wwwroot 中的某些文件夹 的相关文章

随机推荐