[ASP.NET MVC]笔记(三) 成员资格、授权和安全性

时间:2023-03-08 16:24:52
[ASP.NET MVC]笔记(三) 成员资格、授权和安全性
  • 阻止CSRF(跨站请求伪造)

  ASP.NET MVC提供了一个阻止CSRF攻击的好方法

  在每个提交的表单中包含

  

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
//调用@Html.AntiForgeryToken()生成一个防伪标记
@Html.AntiForgeryToken()
<input type="text" name="text"/>
<input type="submit" value="提交" /> }

  在请求的控制器的控制器操作上声明[ValidateAntiForgeryToken]特性

  

[ValidateAntiForgeryToken]
public ActionResult Index(string text)
{
.........
return View();
}
  •  HttpReferrer验证

  验证提交表单的客户端是否在目标站点上

public class IsPostendFromThisSiteAttribute :AuthorizeAttribute
{
public override void OnAuthorize(AuthorizationContext filterContext)
{
if(filterContext.httpContext!=null)
{
if(filterContext.httpContext.Request.UrlReferrer==null)
{
throw new System.Web.HttpException("无效提交");
}
if(filterContext.httpContext.Request.UrlReferrer.Host=!="mysite.com")
{
throw new System.Web.HttpException("非法的提交站点"");
}
}
}
}

  然后再添加自定义的过滤器

[IsPostedFromThisSite]
public ActionResult Register(…)
  •   使用HttpOnly防止Cookie被盗窃获取

  可以在程序中为编写的每个cookie单独设置,告知浏览器除了服务器能修改设置Cookie之外,其他的操作均无效

 

Respone.Cookies["password"]="123456";

Respone.Cookies["password"].HttpOnly=true;

  

  •   使用Bind特效防御重复提交攻击

  Bind特效既可以放在模型类上,也可以放在控制器上。

  1.   白名单方法允许绑定的字段如:[Bind(Include=“Name,Age”)]
  2.   或是黑名单禁止绑定的字段:[Bind(Exclude=“StduentID”)]
  3.   或是直接绑定到视图模型,直接包含自己想要绑定的字段