码迷,mamicode.com
首页 > Web开发 > 详细

MVC3----网站安全性

时间:2015-01-20 12:10:33      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:网站   安全性   

一、防止跨站脚本攻击(XSS)                                                                                                                        

①: @Html.Encode("<script>alert(‘123‘)</script>")
编码后:&lt;script&gt;alert(&#39;123&#39;)&lt;/script&gt;

②: @Html.AttributeEncode("<script>alert(‘123‘)</script>")
编码后:&lt;script>alert(&#39;123&#39;)&lt;/script>

③: @Html.JavascriptEncode()

③: 使用antixss库防御

 

二、防止跨站请求伪造(CSRF)                                                                                                                        

①: 令牌验证(用于表单验证)
在提交表单中加上@Html.AntiForgeryToken(),在控制器中加上[ValidateAntiforgeryToken]

②: HttpReferrer验证(get、post)

新建一个类,继承AuthorizeAttribute(在提交的时候验证):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SchoolManageDomw.Models
{
    public class IsPostedThisSiteAttribute:AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext != null)
            {
                if (filterContext.HttpContext.Request.UrlReferrer == null)
                    throw new Exception("客户端请求的信息为空");
                if (filterContext.HttpContext.Request.UrlReferrer.Host != "localhost")//MySite.com
                    throw new Exception("不安全的请求");
            }
        }
    }
}

 控制器里使用:

        [IsPostedThisSite]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

 

 

本文出自 “程序猿的家--Hunter” 博客,请务必保留此出处http://962410314.blog.51cto.com/7563109/1606025

MVC3----网站安全性

标签:网站   安全性   

原文地址:http://962410314.blog.51cto.com/7563109/1606025

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!