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

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

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




[csharp] view plaincopy
01.using System;  
02.using System.Collections.Generic;  
03.using System.Linq;  
04.using System.Web;  
05.using System.Web.Mvc;  
06.  
07.namespace Admin.MyAttribute  
08.{  
09.    [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 plaincopy
01.调用方法  




[csharp] view plaincopy
01. [MyAttribute.CheckAuthority]  
02.        public ActionResult Index()  
03.        {  
04.             
05.            return View();  
06.        }  
复制代码

转自:http://blog.csdn.net/try530/article/details/7782730

posted @   秋意了了  阅读(472)  评论(0编辑  收藏  举报
编辑推荐:
· 用 .NET NativeAOT 构建完全 distroless 的静态链接应用
· 为什么构造函数需要尽可能的简单
· 探秘 MySQL 索引底层原理,解锁数据库优化的关键密码(下)
· 大模型 Token 究竟是啥:图解大模型Token
· 35岁程序员的中年求职记:四次碰壁后的深度反思
阅读排行:
· 基于Docker+DeepSeek+Dify :搭建企业级本地私有化知识库超详细教程
· 电商平台中订单未支付过期如何实现自动关单?
· 用 .NET NativeAOT 构建完全 distroless 的静态链接应用
· 上周热点回顾(3.31-4.6)
· 爆肝 1 周,为我的白板工具支持了 mermaid 流程图,为 ai 生成流程图铺平道路
点击右上角即可分享
微信分享提示