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

来源:互联网 发布:会议录音软件 编辑:程序博客网 时间:2024/05/22 10:57

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

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

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("/");        }                 }}
调用方法
 [MyAttribute.CheckAuthority]        public ActionResult Index()        {                       return View();        }


原创粉丝点击