asp.net MVC 웹사이트에서 이미지의 핫링크를 방지하는 방법은 무엇입니까?

零下一度
풀어 주다: 2017-06-23 16:07:41
원래의
2451명이 탐색했습니다.

ㅋㅋ                                                                      디렉토리

1.

2. nginx를 통해 사진 핫링크 보호

3. HttpHandler 사용자 정의 처리

4. MVC 사용자 정의 라우팅 규칙을 통한 안티 핫링크

5. MVC 사용자 정의 RouteHandler

6. dModule 거머리 방지

7 지식 포인트 및 관련 리소스 포함

귀하의 웹사이트에 있는 사진이 다른 웹사이트에 의해 도난당하는 것은 매우 역겨운 일입니다. 다음은 사진 도용에 대처하는 방법입니다. 체인에. 먼저 환경에 대해 설명하겠습니다. 저는 MVC4를 사용하고 있으며 IIS7 응용 프로그램 풀은 통합 모드입니다. 다음 구성은 이 환경을 기반으로 합니다.

1. URL 재작성 모듈을 통해

Component

이것은 비교적 간단하고 편리한 방법입니다. 먼저 Url Rewite 공식 웹사이트로 이동하여 URL Rewrite Module 2.0을 다운로드하고 설치하세요. 설치가 완료되면 아래와 같이 IIS 설정에 더 많은 URL 재작성 모듈이 있는 것을 확인할 수 있습니다. 여기에서 URL 액세스 규칙을 설정하고, URL 재작성을 두 번 클릭하고, 인바운드 규칙을 추가할 수 있습니다

조건 (c)에 {HTTP_REFERER}를 추가하고 모드는 ^http://localhost/.*$입니다. 이는 요청 HTTP_REFERER에 http://localhost/ 문자가 포함되어야 함을 의미합니다. 물론 규칙은 자신의 상황에 따라 작성됩니다.

추가하고 저장하면 사이트 web.config 파일의 system.webServer 노드 아래에 rewrite 노드가 생기고 구성은 다음과 같습니다.

<system.webServer><validation validateIntegratedModeConfiguration="false" />    <handlers>  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />  <remove name="OPTIONSVerbHandler" />  <remove name="TRACEVerbHandler" /> 
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /></handlers><rewrite><rules><rule name="防盗链" stopProcessing="true"><match url=".*\.(gif|jpg|png)" /><conditions> <add input="{HTTP_REFERER}" pattern="^http://localhost/.*$" negate="true" /></conditions><action type="Redirect" url="http://www.baidu.com" /></rule></rules></rewrite>
  </system.webServer>
로그인 후 복사
이 구성되었습니다. 효과가 있습니까? ​​테스트 페이지를 만들어

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title></title></head><body><img src="Content/webpage/img/111.jpg" /><img src="111.jpg"/></body></html>
로그인 후 복사

IIS "인바운드 규칙에

HTTP_REFERER

정규식이 구성되어 있으므로 그림이 2개 있습니다. 조건" For
^http://localhost/.*$
규칙이 유효하면 http://localhost/HtmlPage1.html에 액세스할 때 이미지가 정상적으로 표시되어야 하지만, http://127.0을 통해 액세스할 경우에는 이미지가 정상적으로 표시되어야 합니다. 0.1/HtmlPage1.html 그림이 표시되어야 합니다. 이 두 주소를 통해 액세스하면 다음과 같습니다.

구성이 성공했음을 나타냅니다. 물론, URL 재작성 모듈은 이미지 핫링크 보호만을 위한 것이 아닙니다!

2. nginx를 통해

사진 안티 핫링크

안티 핫링크의 원리는 동일하며, 주로 리퍼러를 통해 소스 사이트를 판별합니다. "화이트 리스트"에 없으면 기본 사진을 거부하거나 반환합니다.

location ~.*\.(jpg|gif|png)$ {
     valid_referers none blocked *.abc.com abc.com;     if ($invalid_referer) {
     #rewrite ^/ http://abc.com/error.html;     return 403;
      }
}
로그인 후 복사

location ~.*\.(jpg|gif|png)$  表示所有 以 jpg|gif|png 为后缀名的文件都进行防盗链处理
로그인 후 복사
valid_referers none blocked *.abc.com abc.com;   验证 referer  其中 none 表示直接访问的,不存在referer   blocked为根据防火墙伪装的 referer
로그인 후 복사
  如果图片是放盗链,重定向到 地址 ,一般是图片地址,但是要注意,这个图片地址不只能在此防盗链规则里,否则也访问不到。

对 nginx 配置不熟悉的同学请参考  windows 下配置 Nginx 常见问题
方法步骤: 1 创建自定义 handlers 代码如下,根据 Referre 判断请求来源,如果符合标准,输出文件流,否则停止响应。也可以输出一个特定的图片。
로그인 후 복사
namespace WeiXinDemo.Globals
{/// <summary>/// 测试 Handler 实现图片防盗链/// </summary>public class MyImgHandler : IHttpHandler
    {public bool IsReusable
        {get { return false; }
        }         public void ProcessRequest(HttpContext context)
        {var response = context.Response;var request = context.Request; if (request.UrlReferrer == null || !WebApplication.ImgHost.Equals(request.UrlReferrer.Host))
            {
                response.End();return;
            }var fileName = context.Server.MapPath(request.FilePath);
            response.WriteFile(fileName);if (request.UrlReferrer == null || WebApplication.ImgHost.Equals(request.UrlReferrer.Host))
            {
                response.WriteFile(fileName);
            }else{
                response.End();
            }
        } 
    }
}
로그인 후 복사


2 在web.config 文件 handlers 节点下添加自定义 Handler,满足要求的请求进入  进行处理
로그인 후 복사
<span style="color: #0000ff"><</span><span style="color: #800000">system.webServer</span><span style="color: #0000ff">></span> <span style="color: #0000ff"><</span><span style="color: #800000">handlers</span><span style="color: #0000ff">></span>  <span style="color: #0000ff"><</span><span style="color: #800000">remove </span><span style="color: #ff0000">name</span><span style="color: #0000ff">="ExtensionlessUrlHandler-Integrated-4.0"</span> <span style="color: #0000ff">/></span>  <span style="color: #0000ff"><</span><span style="color: #800000">remove </span><span style="color: #ff0000">name</span><span style="color: #0000ff">="OPTIONSVerbHandler"</span> <span style="color: #0000ff">/></span>  <span style="color: #0000ff"><</span><span style="color: #800000">remove </span><span style="color: #ff0000">name</span><span style="color: #0000ff">="TRACEVerbHandler"</span> <span style="color: #0000ff">/></span>  
      <span style="color: #0000ff"><</span><span style="color: #800000">add </span><span style="color: #ff0000">name</span><span style="color: #0000ff">="ExtensionlessUrlHandler-Integrated-4.0"</span><span style="color: #ff0000"> path</span><span style="color: #0000ff">="*."</span><span style="color: #ff0000"> verb</span><span style="color: #0000ff">="*"</span><span style="color: #ff0000"> type</span><span style="color: #0000ff">="System.Web.Handlers.TransferRequestHandler"</span><span style="color: #ff0000"> preCondition</span><span style="color: #0000ff">="integratedMode,runtimeVersionv4.0"</span> <span style="color: #0000ff">/><br>    <!-- 这是添加的自定义Handler --></span>  <span style="color: #0000ff"><</span><span style="color: #800000">add </span><span style="color: #ff0000">name</span><span style="color: #0000ff">="<span style="color: #0000ff">jpg</span>Handler"</span><span style="color: #ff0000"> path</span><span style="color: #0000ff">="*.jpg"</span><span style="color: #ff0000"> verb</span><span style="color: #0000ff">="*"</span><span style="color: #ff0000"> type</span><span style="color: #0000ff">="WeiXinDemo.Globals.MyImgHandler,WeixinDemo"</span> <span style="color: #0000ff">/><br>    <span style="color: #0000ff"><<span style="color: #800000">add <span style="color: #ff0000">name<span style="color: #0000ff">="<span style="color: #0000ff">png</span>Handler"<span style="color: #ff0000"> path<span style="color: #0000ff">="*.png<span style="color: #0000ff">"<span style="color: #ff0000"> verb<span style="color: #0000ff">="*"<span style="color: #ff0000"> type<span style="color: #0000ff">="WeiXinDemo.Globals.MyImgHandler,WeixinDemo" <span style="color: #0000ff">/><br></span></span><<span style="color: #800000">add <span style="color: #ff0000">name<span style="color: #0000ff">="<span style="color: #0000ff"><span style="color: #800000"><span style="color: #ff0000"><span style="color: #0000ff"><span style="color: #ff0000"><span style="color: #0000ff">bmp</span></span></span></span></span></span>Handler"<span style="color: #ff0000"> path<span style="color: #0000ff">="**.bmp<span style="color: #0000ff">"<span style="color: #ff0000"> verb<span style="color: #0000ff">="*"<span style="color: #ff0000"> type<span style="color: #0000ff">="WeiXinDemo.Globals.MyImgHandler,WeixinDemo" <span style="color: #0000ff">/><br><<span style="color: #800000">add <span style="color: #ff0000">name<span style="color: #0000ff">="<span style="color: #0000ff"><span style="color: #800000"><span style="color: #ff0000"><span style="color: #0000ff"><span style="color: #ff0000"><span style="color: #0000ff"><span style="color: #0000ff">gif</span></span></span></span></span></span></span>Handler"<span style="color: #ff0000"> path<span style="color: #0000ff">="<span style="color: #0000ff">*.gif"<span style="color: #ff0000"> verb<span style="color: #0000ff">="*"<span style="color: #ff0000"> type<span style="color: #0000ff">="WeiXinDemo.Globals.MyImgHandler,WeixinDemo" <span style="color: #0000ff">/><span style="color: #0000ff"></</span><span style="color: #800000">handlers</span><span style="color: #0000ff">></span>      
  <span style="color: #0000ff"></</span><span style="color: #800000">system.webServer</span><span style="color: #0000ff">></span>
로그인 후 복사

<br><strong><span style="font-size: 18px; color: #0000ff"> 4. 通过 </span></strong><strong><span style="font-size: 18px; color: #0000ff">MVC 自定义路由规则防盗链<br></span></strong>    <span style="font-size: 14px"><br>    首先我们要在 web.config 文件里 <span style="color: #800000">system.webServer</span> 节点下 设置<span style="color: #0000ff"><<span style="color: #993300">modules <span style="color: #ff0000">runAllManagedModulesForAllRequests<span style="color: #0000ff">="true" <span style="color: #0000ff">/>  <span style="color: #000000">同时还要在 <span style="color: #ff6600">RouteConfig.cs</span> 文件里添加 routes.RouteExistingFiles = true;确保所有路由都通过 RouteCollection 匹配 。<br></span></span></span><span style="font-size: 14px">在这里我们需要了解 UrlRoutingModule,它是System.Web.Routing的一部分。UrlRoutingModule用于检验请求的url和本地硬盘 中的文件能不能相匹配。</span>如果匹配,则交给IIS处理。如果不匹配它会检验 RouteCollection 来决定能不能继续传递请求。而设置了 <span style="font-size: 14px"><span style="color: #0000ff"><span style="color: #993300"><span style="color: #ff0000">runAllManagedModulesForAllRequests<span style="color: #0000ff">="true"</span></span></span></span></span> 后,会改变默认行为,所有请求都须要 运用 Routing来处理。<br>
로그인 후 복사
<system.webServer><validation validateIntegratedModeConfiguration="false" /><modules runAllManagedModulesForAllRequests="true" />    <handlers>  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />  <remove name="OPTIONSVerbHandler" />  <remove name="TRACEVerbHandler" /> 
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /></handlers> 
  </system.webServer>
로그인 후 복사
구성 파일이 설정된 후 사용자 정의 라우팅 규칙을 추가합니다. 사용자 정의 라우팅 규칙의 구현 코드 실제로, 정규식을 사용하여 현재 요청이 규칙을 준수하는지 확인하고, 그렇지 않으면 다른 라우팅 규칙을 일치시킵니다.
<br>
로그인 후 복사
로그인 후 복사
namespace WeiXinDemo.Globals
{/// <summary>/// 图片路由规则(自定义)/// </summary>public class ImgRouteRule : IRouteConstraint
    {  public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {var regex = new Regex(@"/[^/]+(.jpg|.bmp|.gif|.png)");var result = regex.IsMatch(httpContext.Request.RawUrl); return result;
        }
    }
}
로그인 후 복사
<br>
로그인 후 복사
로그인 후 복사

    这样就造成了一个问题,所有的请求(比如 .css  .js  .htm 等等)都去路由规则里面去匹配,如果在路由规则里面匹配不到那么就会返回 404,如何避免呢?通过 RouteConfig.cs 文件配置忽略。

public class RouteConfig
    {public static void RegisterRoutes(RouteCollection routes)
        {//确保所有路由都通过 RouteCollection 匹配(图片防盗链)routes.RouteExistingFiles = true;//忽略 json,html,js,css文件routes.IgnoreRoute("{*pathInfo}", new { pathInfo = @".+(.json|.html|.js|.css)" });
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); //符合路由规则的转到控制器 ImgRule/Index 处理 (自定义路由规则实现 图片防盗链)            routes.MapRoute(
                name: "ImagesRoute",
                url: "{*catchall}",
                defaults: new { controller = "ImgRule", action = "Index" },// ImgRouteRule 为自定义路由规则,符合此规则,进入路由 访问 ImgRule/Index constraints: new { customConstraint = new ImgRouteRule() },//控制器类命名空间namespaces: new[] { "WeiXinDemo.Controllers" });

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );            
        }
    }
로그인 후 복사

    在上面的代码里配置了 "ImagesRoute"   的路由,使用的自定义路由规则,当满足规则时,跳转到 ImgRule/Index 去处理,处理代码跟使用 HttpHandler 类似

 public class ImgRuleController : Controller
    {// GET: ImgRulepublic FileStreamResult Index()
        {var fPath = Server.MapPath("~" + Request.FilePath);if (Request.UrlReferrer == null)   return null;            if (!System.IO.File.Exists(fPath) || !WebApplication.ImgHost.Equals(Request.UrlReferrer.Host) || !WebApplication.ImgHost.Equals(Request.UrlReferrer.Host))            return null; return GetFile(fPath);
        }private FileStreamResult GetFile(string fPath)
        { return File(new FileStream(fPath, FileMode.Open, FileAccess.Read), GetContentType(Request.FilePath));
        }private static string GetContentType(string url)
        {switch (Path.GetExtension(url))
            {case ".gif":return "Image/gif";case ".jpg":return "Image/jpeg";case ".png":return "Image/png";default:break;
            }return null;
        }
    }
로그인 후 복사
<br>5. 通过 MVC 自定义 RouteHandler 防盗链
로그인 후 복사
1  文件配置同,也要开启 
2 创建自定义路由,自定义路实现代码如下  ,同时还有自定义路由调用的  ,
로그인 후 복사
using System.IO;using System.Text.RegularExpressions;using System.Web;using System.Web.Routing;namespace WeiXinDemo.Globals
{/// <summary>/// 测试自定义 RouteHandler 图片防盗链/// </summary>public class ImageRouteHandler : IRouteHandler
    {public IHttpHandler GetHttpHandler(RequestContext requestContext)
        { return new ImageHandler();
        }
    }     /// <summary>/// 自定义路由调用的 HttpHandler/// </summary>public class ImageHandler : IHttpHandler
    {public ImageHandler()
        {
            
        }         public bool IsReusable
        {get{return true;
            }
        } public void ProcessRequest(HttpContext context)
        {var response = context.Response;var request = context.Request; if (request.UrlReferrer == null || !WebApplication.ImgHost.Equals(request.UrlReferrer.Host))
            {
                response.End();return;
            }var fileName = context.Server.MapPath(request.FilePath);
            response.WriteFile(fileName);  
        }
    }
}
로그인 후 복사

     RouteConfig.cs 文件配置 如下,这里指定了 对根目录下的 jpg 文件的访问进入指定路由处理程序 ImageRouteHandler。    其实这里可以把图片都放在某一个特定文件夹下,然后对这个文件夹下文件的访问做放盗链。

namespace WeiXinDemo
{public class RouteConfig
    {public static void RegisterRoutes(RouteCollection routes)
        {//确保所有路由都通过 RouteCollection 匹配(图片防盗链)routes.RouteExistingFiles = true;//忽略 json,html,js,css文件routes.IgnoreRoute("{*pathInfo}", new { pathInfo = @".+(.json|.html|.js|.css)" });
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");//图片防盗链routes.Add("ImagesRoute",new Route("{name}.jpg", new ImageRouteHandler())); routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
            
        }
    }
}
로그인 후 복사
<br>6. 通过 HttpModule 防盗链
로그인 후 복사
1. 修改 web.config 配置文件
로그인 후 복사
<system.webServer><modules runAllManagedModulesForAllRequests="true" >  <add   name="ImgModule" type="WeiXinDemo.Globals.ImageModel,WeiXinDemo"/></modules> <handlers>  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />  <remove name="OPTIONSVerbHandler" />  <remove name="TRACEVerbHandler" /> </handlers>       
  </system.webServer>
로그인 후 복사

2. 创建实现 IHttpModule 接口的 ImageModel

     +=  BeginRequest(= regex =  Regex( request = (!regex.IsMatch(request.RawUrl))  (request.UrlReferrer ==  || ! fileName =
로그인 후 복사

3.  RouteConfig.cs 文件忽略不需要防盗链的静态资源

using System.Web.Mvc;using System.Web.Routing;namespace WeiXinDemo
{public class RouteConfig
    {public static void RegisterRoutes(RouteCollection routes)
        {//确保所有路由都通过 RouteCollection 匹配(图片防盗链)routes.RouteExistingFiles = true;//忽略 json,html,js,css文件routes.IgnoreRoute("{*pathInfo}", new { pathInfo = @".+(.json|.html|.js|.css)" });
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );            
        }
    }
}
로그인 후 복사

 

7. 涉及知识<br>
로그인 후 복사

本文只做了一件事情,图片防盗链,其实从不同的实现方式来看它涉及到不同的知识。

1. URL Rewrite Module  组件的使用

 如何使用mod_rewrite模块完成URL重写

 Creating Rewrite Rules for the URL Rewrite Module

2.  Nginx

借助Nginx搭建反向代理服务器

使用nginx实施负载均衡

3. IIS 工作原理,asp.net 管线

 IIS是如何处理ASP.NET请求的

ASP.NET那点不为人知的事

IIS 内部运行机制

ASP.NET MVC5请求管道和生命周期

ASP.NET MVC请求处理管道生命周期的19个关键环节(1-6)

4. Mvc UrlRouting 处理机制

MVC之前的那点事儿系列(8):UrlRouting的理解

 

    本文只是在这里探讨了一下实现防盗链的方法,没有考虑性能的问题,如果考虑性能跟简便性,我个人喜欢用 第 1 和第 2种实现方式,第 3种 次之。 条条大路通罗马,就看那种方法最适合。

     

위 내용은 asp.net MVC 웹사이트에서 이미지의 핫링크를 방지하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!