利用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();
}
可以广泛应用于表单提交,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();
}
相关文章推荐
- 分享微信开发Html5轻游戏中的几个坑
- 100 个最佳 Ubuntu 应用(中)
- 在 AppImage、Flathub 和 Snapcraft 平台上搜索 Linux 应用
- 24 个必备的 Linux 应用程序
- 注册表趣味应用小集
- 远程控制技术的应用
- 在线用表单建立文件夹
- 路由器访问列表的应用
- Jquery 表单取值赋值的一些基本操作
- xDSL技术及其应用
- 基于XML的桌面应用
- SQL Server 2008 R2 应用及多服务器管理
- javascript 表单的友好用户体现
- Node.js 应用跑得更快 10 个技巧
- js 提交和设置表单的值
- Zend的MVC机制使用分析(二)
- 攻克CakePHP系列二 表单数据显示
- ASP.NET MVC 4 捆绑和缩小实例介绍
- ASP.NET Mvc开发之查询数据
- ASP.NET MVC中将控制器分离到类库的实现