利用AuthorizeAttribute属性简单避免 MVC 中的跨域攻击

来源:互联网 发布:机智交易软件 编辑:程序博客网 时间:2024/05/17 00:05

跨域攻击---自然来路页面和目标页面不在同一个域下,所以直接判断来路域和当前自己的域就可以了。

可以广泛应用于表单提交,ajax调用或者某些不想让用户直接输入网址看到的页面

[csharp] view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace Admin.MyAttribute  
  8. {  
  9.     [AttributeUsage(AttributeTargets.All, Inherited = true)]  
  10.     public class CheckAuthority : AuthorizeAttribute  
  11.     {  
  12.   
  13.         protected override bool AuthorizeCore(HttpContextBase httpContext)  
  14.         {  
  15.             bool Pass = true;  
  16.             Uri UrlReferrer = httpContext.Request.UrlReferrer;//获取来路  
  17.             if (UrlReferrer == null)  
  18.             {  
  19.                 httpContext.Response.StatusCode = 401;//无权限状态码  
  20.   
  21.                 Pass = false;  
  22.             }  
  23.             else   
  24.             {  
  25.                  Uri ThisUrl = httpContext.Request.Url;//当前请求的URL  
  26.                 if (UrlReferrer.Authority  != ThisUrl.Authority)  
  27.                 {  
  28.                     httpContext.Response.StatusCode = 401;//无权限状态码  
  29.                     Pass = false;  
  30.                 }  
  31.             }  
  32.   
  33.   
  34.             return Pass;  
  35.         }  
  36.   
  37.          
  38.   
  39.         protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)  
  40.         {  
  41.             base.HandleUnauthorizedRequest(filterContext);  
  42.             if (filterContext.HttpContext.Response.StatusCode == 401)  
  43.                 filterContext.Result = new RedirectResult("/");  
  44.         }  
  45.   
  46.          
  47.   
  48.         
  49.     }  
  50. }  
[csharp] view plain copy
  1. 调用方法  
[csharp] view plain copy
  1.  [MyAttribute.CheckAuthority]  
  2.         public ActionResult Index()  
  3.         {  
  4.              
  5.             return View();  
  6.         }  
0 0
原创粉丝点击