阻止访问图像链接

时间:2021-04-26 07:47:13

标签: c# asp.net-core

我正在使用 ASP.NET Core 开发上传文件功能

每个用户都将他们的图片上传到一个单独的文件夹:wwwroot/images/{userId}/{filename}.jpg

问题是,如果其他用户(例如:userId = 3)和他们的 ID 知道其他用户的 ID(例如:userId = 1)和他/她上传的图片文件名,那么他们可以很容易地访问他/她的文件以上格式的网址:https://localhost:3333/images/1/user1Secret.jpg

我想限制每个用户在他们文件夹中的图片,只有登录用户才能访问自己的图片,其他用户或未登录用户无法通过浏览器地址栏中的 URL 格式访问这些图片,它可能会返回一个 403 页面或有点

我该怎么做? 谢谢大家

1 个答案:

答案 0 :(得分:1)

请先阅读以下关于静态文件授权的文档:

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

这是整个工作演示:

1.将 images 文件夹移到 wwwroot 之外。

2.在任何控制器中添加此类操作:

[Authorize]
[Route("myimages/{userId}/{filename}")]
public IActionResult Image(string userId,string filename)
{
    var CurrentUserId = User.FindFirst(ClaimTypes.NameIdentifier).Value;

    if (CurrentUserId == userId)
    {
        var file = Path.Combine(Directory.GetCurrentDirectory(),
                                "images", userId, filename);
        string ext = System.IO.Path.GetExtension(filename).ToLower();
        Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
        //get the mimetype of the file
        string mimeType = regKey.GetValue("Content Type").ToString();

        return PhysicalFile(file, mimeType);
    }
    return new ForbidResult();
}

3.配置Startup.cs:

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
            Path.Combine(env.ContentRootPath, "images")),
    RequestPath = "/myimages"
});

app.UseAuthorization();
相关问题