【问题标题】:ASP.NET Core 2.2 Prevent Direct URL Access to Document/FileASP.NET Core 2.2 防止对文档/文件的直接 URL 访问
【发布时间】:2019-05-28 01:25:33
【问题描述】:

我有一堆文件存储在一个目录中。这些文件的链接存储在数据库中,例如

https://localhost:44325/Repositories/Aopdio/2019/05/QWNjb3VX0FNT1NUSElSRF9LTA==.pdf

当我登录到我的应用程序时,我可以通过应用程序访问文件。但是,当我复制此链接并将其粘贴到另一个浏览器中时,该文件仍会打开。

有没有办法防止这种情况发生?我希望仅从应用程序提供内容。

这是我的startup.cs

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(RepositoryManager.GetBasePath(Environment.GetEnvironmentVariable("APPONE_REPOSITORY"))),
    RequestPath = RepositoryManager.GetRequestPath(Environment.GetEnvironmentVariable("APPONE_REPOSITORY"))
});
app.UseStaticFiles(
    new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Resources")),
        RequestPath = "/Resources"
    }
);

这是我尝试实现的中间件:

在 Startup.cs 中

app.UseRequestMiddleware();

中间件

public class RequestMiddleware
{
    private readonly RequestDelegate next;

    public RequestMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context, Func<Task> next)
    {
        var test = context;
    }
}

调用中间件的扩展,在Startup.cs中被调用

public static class RequestMiddlewareExtension
    {
        public static IApplicationBuilder UseRequestMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestMiddleware>();
        }
    }
}

但是,我收到此错误:

InvalidOperationException: Unable to resolve service for type 'System.Func`1[System.Threading.Tasks.Task]' while attempting to Invoke middleware 'App.ClassLibrary.Middleware.RequestMiddleware'.

【问题讨论】:

  • Repositories 文件夹是否存储在 wwwroot 下?
  • 不,它存储在解决方案之外的另一个文件夹中。
  • 我编辑了我的问题以包含我的 startup.cs
  • 服务器识别哪个请求来自您的应用程序的逻辑是什么?您可以在app.UseStaticFiles之前实现您的中间件,并检查请求是否满足您访问静态文件的请求。
  • @TaoZhou 我没有任何逻辑来确定哪个请求来自我的应用程序。我应该有类似的东西吗?有没有可用的例子?

标签: c# asp.net asp.net-mvc asp.net-core


【解决方案1】:

在 app.UseStaticFiles() 的默认配置中,只提供 wwwroot 下的文件。如果直接提供该目录之外的文件,则要么您已从根文件夹为整个应用程序启用静态文件,要么您已在 IIS 上启用目录浏览。您可以检查和禁用它们。

[更新] 当您使用 UseStaticFiles() 提供文件时,请求方法不会通过正常的中间件管道传递。所以你不能拥有像 Authenticate/Authorize 这样的常规中间件功能。您可以拥有一个返回 FileResult 的存储库控制器,也可以拥有一个自定义中间件,例如 the one here

【讨论】:

  • 感谢您的回答。我编辑了我的问题以包括我的 startup.cs。
  • 这些行似乎服务于那些静态文件: app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(RepositoryManager.GetBasePath(Environment.GetEnvironmentVariable("APPONE_REPOSITORY"))), RequestPath = RepositoryManager.GetRequestPath( Environment.GetEnvironmentVariable("APPONE_REPOSITORY")) });
  • 是的,我需要从那里为他们服务。有没有办法确保只有当用户在我的应用程序中时才能使用链接
  • 从 wwwroot 而不是外部文件夹提供它会更好吗?
  • 我认为这没什么区别
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 2012-05-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-28
  • 2023-02-16
  • 1970-01-01
相关资源
最近更新 更多