在ASP.NET Core中,通过中间件防止图片盗链是一种有效的方法,以下是一个详细的示例,展示如何实现这一功能:

原理解释
防盗链的基本原理是利用HTTP协议中的Referer字段来追踪请求的来源,如果请求的来源不是预期的网站,则拒绝访问或者返回一个特定的页面,这种方法可以在一定程度上防止图片被盗用。
创建自定义中间件
我们需要创建一个自定义中间件类来实现防盗链功能,这个中间件会检查每个请求的Referer头,如果Referer不是来自我们的网站,则返回一个404错误页面。
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading.Tasks;
public class HotlinkingPreventionMiddleware
{
private readonly RequestDelegate _next;
private readonly string _wwwrootFolder;
public HotlinkingPreventionMiddleware(RequestDelegate next, IWebHostEnvironment env)
{
_next = next;
_wwwrootFolder = env.WebRootPath;
}
public async Task Invoke(HttpContext context)
{
var applicationUrl = $"{context.Request.Scheme}://{context.Request.Host.Value}";
var urlReferrer = context.Request.Headers["Referer"].ToString();
if (!string.IsNullOrEmpty(urlReferrer) && !urlReferrer.StartsWith(applicationUrl))
{
var unauthorizedImagePath = Path.Combine(_wwwrootFolder, "images", "unauthorized.png");
await context.Response.SendFileAsync(unauthorizedImagePath);
}
else
{
await _next(context);
}
}
}
注册中间件
我们需要在ASP.NET Core的启动配置中注册这个中间件,确保这个中间件在静态文件中间件之前调用,以便在处理静态文件请求之前进行防盗链检查。
public class Startup
{
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<HotlinkingPreventionMiddleware>(env);
app.UseStaticFiles();
// 其他中间件和路由配置...
}
}
测试防盗链功能
为了测试这个防盗链功能,我们可以在不同的网站上引用我们网站上的图片,如果我们的图片URL是https://example.com/images/test.jpg,我们可以在其他网站上尝试引用这个图片URL,如果引用成功,说明防盗链功能没有生效;如果显示的是unauthorized.png图片,说明防盗链功能生效了。

问题与解答
问题1: 如果我想允许特定的外部网站引用我的图片,应该怎么办?
解答:你可以在中间件中添加一个白名单机制,允许特定网站的Referer通过,你可以修改中间件的Invoke方法如下:
public async Task Invoke(HttpContext context)
{
var applicationUrl = $"{context.Request.Scheme}://{context.Request.Host.Value}";
var urlReferrer = context.Request.Headers["Referer"].ToString();
var allowedSites = new List<string> { "https://allowedsite.com" };
if (!string.IsNullOrEmpty(urlReferrer) && !urlReferrer.StartsWith(applicationUrl) && !allowedSites.Contains(urlReferrer))
{
var unauthorizedImagePath = Path.Combine(_wwwrootFolder, "images", "unauthorized.png");
await context.Response.SendFileAsync(unauthorizedImagePath);
}
else
{
await _next(context);
}
}
问题2: 如果攻击者伪造Referer头绕过防盗链怎么办?
解答:虽然可以通过伪造Referer头来绕过简单的防盗链检查,但这种方法并不是完全可靠的,为了提高安全性,可以考虑使用更复杂的验证机制,如基于Token的验证或者结合服务器端日志分析等方法来检测和阻止盗链行为,还可以考虑使用CDN服务提供的防盗链功能,这些服务通常提供了更强大和灵活的防盗链选项。

各位小伙伴们,我刚刚为大家分享了有关“Asp.Net Core 通过中间件防止图片盗链的实例”的知识,希望对你们有所帮助。如果您还有其他相关问题需要解决,欢迎随时提出哦!