【问题标题】:Asp.net core Protect Folder out side wwwrootAsp.net core Protect 外部 wwwroot 文件夹
【发布时间】:2021-04-26 19:44:19
【问题描述】:

我正在创建一个 asp.net 核心应用程序并使用 .Net5。我正在 www-root 文件夹之外上传文件。这是我的目录配置。

 app.UseFileServer(new FileServerOptions
            {
                FileProvider = new PhysicalFileProvider(@$"{Configuration["AppConfiguration:PhysicalDirectoryBasePath"]}"),
                RequestPath = new PathString("/app-data"),
                EnableDirectoryBrowsing = false
            });

我想保护该文件夹,以便没有公共用户可以访问它。我想在访问文件之前检查标题

header contains app-token then allow file to access otherwise not

我无法停止公共用户的文件访问。如何做到这一点?

【问题讨论】:

  • 一种解决方案是从 startup.cs 文件中删除上述代码,然后通过控制器提供文件。但是有很多种文件,例如 html、js 和 images 。如何处理所有这些文件?
  • 只需添加一个控制器动作,将文件发送到网络,return File(path);
  • 你不认为它会从系统中暴露我的物理路径吗?
  • 不,这会保护您的文件系统,您必须以某种方式识别文件,我不会将“路径”作为路由参数发送。
  • 好的,知道了。这样我也可以检查上下文标题?对吗?

标签: asp.net-mvc asp.net-core .net-core .net-5


【解决方案1】:

您可以为此使用middleware。即Map 允许为路径执行所需的中间件

app.Map("/app-data", appBuilder =>
{
    appBuilder.UseFilter();

    appBuilder.UseFileServer(new FileServerOptions
    {
        FileProvider = new PhysicalFileProvider($@"{Configuration["AppConfiguration:PhysicalDirectoryBasePath"]}"),
        RequestPath = new PathString(""), //empty, because root path is in Map now
        EnableDirectoryBrowsing = false
    });
}

过滤中间件

public class FilterMiddleware
{
    private readonly RequestDelegate _next;

    public FilterMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        if (httpContext.Request.Headers["API-KEY"] == "secret key")
        {
            //proceed serving files
            await _next(httpContext);
        }
        else
        {
            //return you custom response
            await httpContext.Response.WriteAsync("Forbidden");
        }
    }
}

扩展类允许调用UseFilter

public static class FilterMiddlewareExtensions
{
    public static IApplicationBuilder UseFilter(this IApplicationBuilder applicationBuilder)
    {
        return applicationBuilder.UseMiddleware<FilterMiddleware>();
    }
}

【讨论】:

  • 好的,我需要将代码保留在我的问题中还是应该删除该代码并仅使用中间件?
  • @HaseebKhan 您需要用我的答案中的第一个代码 sn-p 替换您的代码。这是app.Map( { appBuilder.UseFilter(); appBuilder.UseFileServer(...); })
  • 好的,我现在正在检查。
  • 您的解决方案运行良好。谢谢大佬
  • 我面临的一个问题是当我的路径包含 .zip 文件时,中间件让它通过。我不知道为什么,但即使调试器也没有命中
猜你喜欢
  • 2023-04-08
  • 2019-06-10
  • 2020-09-07
  • 2018-12-22
  • 2016-07-17
  • 2019-12-30
  • 2022-01-22
  • 1970-01-01
  • 2018-06-04
相关资源
最近更新 更多