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

本文介绍了一种通过检查HTTP请求来源以防止跨域攻击的方法。该方法通过对比请求来源域名与当前请求处理域名是否一致来判断是否存在跨域行为。适用于表单提交、AJAX调用等场景。

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

可以广泛应用于表单提交,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();
        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值