Dotnet 核心:阻止通过浏览器直接访问图像的最佳方法是什么?
Dotnet core: What is the best way to block direct access to images via the browser?
我设置了一个 dotnet 核心 API(在 IIS8 上),它打开了一个 (aurelia) 应用程序的上传文件夹。我已经像这样打开了对该文件夹的访问
app.UseFileServer(new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(Configuration["ApiSettings:UploadsFolder"]),
RequestPath = new PathString("/uploads/"),
EnableDirectoryBrowsing = true
});
这很好用,因为应用程序可以通过 URL 打开应用程序中上传的图像。现在,当直接在浏览器中输入 URL 时,我想阻止对这些图像的访问。我看过 C# 解决方案,但找不到 dotnet 核心解决方案。
我正在使用中间件拦截发送到 api 的请求。但是无法设法通过浏览器拦截特定的图像请求并阻止它们。唯一允许访问图像的应该是我在固定域上的 aurelia 应用程序。
public async Task Invoke(HttpContext context)
{
StringValues referer;
context.Request.Headers.TryGetValue("Referer", out referer);
// Referer will contain the full URL of the image when requested
// via the browser. When its requested differently it will contain
// the url of the requesting application
if (referer.Any() && referer.First().Contains("/uploads/"))
{
context.Response.StatusCode = 401;
return;
}
await _next.Invoke(context);
}
谁能告诉我最好的方法是阻止对图像的直接访问并只允许特定应用程序加载图像?
静态文件请求没有到达您的中间,因为 IIS 的静态文件处理程序在请求到达 .NET Core 之前处理该请求。
只需从 IIS 的 "Modules" 功能中删除 "StaticFileModule"(对于您的 .NET Core 网站或在服务器级别),请求就会通过。
这是提到这个的官方 .NET Core 文档:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files#considerations
编辑
根据文档:
If the IIS static file handler is enabled and the ASP.NET Core Module (ANCM) is not correctly configured (for example if web.config was not deployed), static files will be served.
这其实和我上面说的相反。虽然删除静态文件处理程序应该仍然可以解决问题,但您还应该检查您的 ANCM 配置。
我设置了一个 dotnet 核心 API(在 IIS8 上),它打开了一个 (aurelia) 应用程序的上传文件夹。我已经像这样打开了对该文件夹的访问
app.UseFileServer(new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(Configuration["ApiSettings:UploadsFolder"]),
RequestPath = new PathString("/uploads/"),
EnableDirectoryBrowsing = true
});
这很好用,因为应用程序可以通过 URL 打开应用程序中上传的图像。现在,当直接在浏览器中输入 URL 时,我想阻止对这些图像的访问。我看过 C# 解决方案,但找不到 dotnet 核心解决方案。
我正在使用中间件拦截发送到 api 的请求。但是无法设法通过浏览器拦截特定的图像请求并阻止它们。唯一允许访问图像的应该是我在固定域上的 aurelia 应用程序。
public async Task Invoke(HttpContext context)
{
StringValues referer;
context.Request.Headers.TryGetValue("Referer", out referer);
// Referer will contain the full URL of the image when requested
// via the browser. When its requested differently it will contain
// the url of the requesting application
if (referer.Any() && referer.First().Contains("/uploads/"))
{
context.Response.StatusCode = 401;
return;
}
await _next.Invoke(context);
}
谁能告诉我最好的方法是阻止对图像的直接访问并只允许特定应用程序加载图像?
静态文件请求没有到达您的中间,因为 IIS 的静态文件处理程序在请求到达 .NET Core 之前处理该请求。
只需从 IIS 的 "Modules" 功能中删除 "StaticFileModule"(对于您的 .NET Core 网站或在服务器级别),请求就会通过。
这是提到这个的官方 .NET Core 文档:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files#considerations
编辑
根据文档:
If the IIS static file handler is enabled and the ASP.NET Core Module (ANCM) is not correctly configured (for example if web.config was not deployed), static files will be served.
这其实和我上面说的相反。虽然删除静态文件处理程序应该仍然可以解决问题,但您还应该检查您的 ANCM 配置。