您的位置:首页 > 其它

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

2016-04-14 10:59 316 查看
跨域攻击---自然来路页面和目标页面不在同一个域下,所以直接判断来路域和当前自己的域就可以了。

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

[csharp] view
plain copy

using System;  

using System.Collections.Generic;  

using System.Linq;  

using System.Web;  

using System.Web.Mvc;  

  

namespace Admin.MyAttribute  

{  

    [AttributeUsage(AttributeTargets.All, Inherited = true)]  

    public class CheckAuthority : AuthorizeAttribute  

    {  

  

        protected override bool AuthorizeCore(HttpContextBase httpContext)  

        {  

            bool Pass = true;  

            Uri UrlReferrer = httpContext.Request.UrlReferrer;//获取来路  

            if (UrlReferrer == null)  

            {  

                httpContext.Response.StatusCode = 401;//无权限状态码  

  

                Pass = false;  

            }  

            else   

            {  

                 Uri ThisUrl = httpContext.Request.Url;//当前请求的URL  

                if (UrlReferrer.Authority  != ThisUrl.Authority)  

                {  

                    httpContext.Response.StatusCode = 401;//无权限状态码  

                    Pass = false;  

                }  

            }  

  

  

            return Pass;  

        }  

  

         

  

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)  

        {  

            base.HandleUnauthorizedRequest(filterContext);  

            if (filterContext.HttpContext.Response.StatusCode == 401)  

                filterContext.Result = new RedirectResult("/");  

        }  

  

         

  

        

    }  

}  

[csharp] view
plain copy

调用方法  

[csharp] view
plain copy

 [MyAttribute.CheckAuthority]  

        public ActionResult Index()  

        {  

             

            return View();  

        }  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mvc 应用 表单