http://stackoverflow.com/questions/29939566/preventing-cross-site-request-forgery-csrf-attacks-in-asp-net-web-forms

1.在Master页面添加以下代码

C#

public partial class SiteMaster : MasterPage
{
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue; protected void Page_Init(object sender, EventArgs e)
{
//First, check for the existence of the Anti-XSS cookie
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue; //If the CSRF cookie is found, parse the token from the cookie.
//Then, set the global page variable and view state user
//key. The global variable will be used to validate that it matches
//in the view state form field in the Page.PreLoad method.
if (requestCookie != null
&& Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
//Set the global token variable so the cookie value can be
//validated against the value in the view state form field in
//the Page.PreLoad method.
_antiXsrfTokenValue = requestCookie.Value; //Set the view state user key, which will be validated by the
//framework during each request
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
//If the CSRF cookie is not found, then this is a new session.
else
{
//Generate a new Anti-XSRF token
_antiXsrfTokenValue = Guid.NewGuid().ToString("N"); //Set the view state user key, which will be validated by the
//framework during each request
Page.ViewStateUserKey = _antiXsrfTokenValue; //Create the non-persistent CSRF cookie
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
//Set the HttpOnly property to prevent the cookie from
//being accessed by client side script
HttpOnly = true, //Add the Anti-XSRF token to the cookie value
Value = _antiXsrfTokenValue
}; //If we are using SSL, the cookie should be set to secure to
//prevent it from being sent over HTTP connections
if (FormsAuthentication.RequireSSL &&
Request.IsSecureConnection)
{
responseCookie.Secure = true;
} //Add the CSRF cookie to the response
Response.Cookies.Set(responseCookie);
} Page.PreLoad += master_Page_PreLoad;
} protected void master_Page_PreLoad(object sender, EventArgs e)
{
//During the initial page load, add the Anti-XSRF token and user
//name to the ViewState
if (!IsPostBack)
{
//Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey; //If a user name is assigned, set the user name
ViewState[AntiXsrfUserNameKey] =
Context.User.Identity.Name ?? String.Empty;
}
//During all subsequent post backs to the page, the token value from
//the cookie should be validated against the token in the view state
//form field. Additionally user name should be compared to the
//authenticated users name
else
{
//Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] !=
(Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of " +
"Anti-XSRF token failed.");
}
}
}
}

VB.NET

 Private Const AntiXsrfTokenKey As String = "__AntiXsrfToken"
Private Const AntiXsrfUserNameKey As String = "__AntiXsrfUserName"
Private _antiXsrfTokenValue As String Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
' The code below helps to protect against XSRF attacks
Dim requestCookie = Request.Cookies(AntiXsrfTokenKey)
Dim requestCookieGuidValue As Guid
If requestCookie IsNot Nothing AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue) Then
' Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value
Page.ViewStateUserKey = _antiXsrfTokenValue
Else
' Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N")
Page.ViewStateUserKey = _antiXsrfTokenValue Dim responseCookie = New HttpCookie(AntiXsrfTokenKey)
responseCookie.HttpOnly = True
responseCookie.Value = _antiXsrfTokenValue
If FormsAuthentication.RequireSSL AndAlso Request.IsSecureConnection Then
responseCookie.Secure = True
End If
Response.Cookies.Set(responseCookie)
End If
AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
End Sub Protected Sub master_Page_PreLoad(sender As Object, e As EventArgs)
If Not IsPostBack Then
' Set Anti-XSRF token
ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, [String].Empty)
Else
' Validate the Anti-XSRF token
If DirectCast(ViewState(AntiXsrfTokenKey), String) <> _antiXsrfTokenValue OrElse DirectCast(ViewState(AntiXsrfUserNameKey), String) <> (If(Context.User.Identity.Name, [String].Empty)) Then
Throw New InvalidOperationException("Validation of Anti-XSRF token failed.")
End If
End If
End Sub

2.logout的时候清除相关cookie(这里很重要,否则没有效果)

        Session.Abandon()
'delete the session and antixsrfToken cookies
Dim sessionCookie = Response.Cookies("ASP.NET_SessionId")
Dim antiCookie = Response.Cookies("__AntiXsrfToken")
sessionCookie.Expires = DateTime.Now.AddHours(-)
antiCookie.Expires = DateTime.Now.AddHours(-)
Response.Cookies.Add(sessionCookie)
Response.Cookies.Add(antiCookie)
Response.Redirect("./login.aspx", False)

ASP.NET CSRF 解决【网摘】的更多相关文章

  1. Delphi 中DataSnap技术网摘

    Delphi2010中DataSnap技术网摘 一.为DataSnap系统服务程序添加描述 这几天一直在研究Delphi 2010的DataSnap,感觉功能真是很强大,现在足有理由证明Delphi7 ...

  2. Feedly订阅Blog部落格RSS网摘 - Blog透视镜

    网络信息爆炸的时代,如何更有效率地阅读文章,订阅RSS网摘,可以快速地浏览文章标题,当对某些文章有兴趣时,才点下连结连到原网站,阅读更详细的文章,Feedly Reader阅读器除了提供在线版订阅RS ...

  3. Bloglines订阅Blog部落格RSS网摘 - Blog透视镜

    网络信息蓬勃发展,Blog部落格越来越普及,如果逐一地去浏览网站,势必费时费力,倘若信息可以自己送上门,那就可以节省不少时间,就好像看报纸的标题,有兴趣才点连结,进到网站浏览文章内容,Blogline ...

  4. TCP/IP协议头部结构体(网摘小结)(转)

    源:TCP/IP协议头部结构体(网摘小结) TCP/IP协议头部结构体(转) 网络协议结构体定义 // i386 is little_endian. #ifndef LITTLE_ENDIAN #de ...

  5. Vim命令快捷键(网摘)

    Vim命令快捷键(网摘) 原文出处:[?---->home]

  6. c#与C++类型转换网摘

    转载自 C++和C#转换 https://www.cnblogs.com/zjoch/p/4147182.html c#与C++类型转换,网摘 //c++:HANDLE(void   *)       ...

  7. ubuntu解决网易云无法打开

    最近首次入手ubuntu18 摸索了很久,当然网易云是不可缺少的一部分,在配置好各种环境+程序后,也找到了解决网易云的方法了. 首先安装好网易云 默认情况下需要在终端使用 sudo 才能运行 解决的办 ...

  8. Python入门及容易!网摘分享给大家!

    Python:Python学习总结 背景 PHP的$和->让人输入的手疼(PHP确实非常简洁和强大,适合WEB编程),Ruby的#.@.@@也好不到哪里(OO人员最该学习的一门语言). Pyth ...

  9. 采访ServiceStack的项目领导Demis Bellot——第1部分(网摘)

    ServiceStack是一个开源的.支持.NET与Mono平台的REST Web Services框架.InfoQ有幸与Demis Bellot深入地讨论了这个项目.在这篇两部分报道的第1部分中,我 ...

随机推荐

  1. 短路运算符&&、或运算符||的理解

    一.短路运算符&& 1.当只有两个表达式的时候(如a&&b),先看第一个表达式转换成布尔值的结果若为真,那么再看第二个表达式转换成布尔值的结果,就可以返回该表达式的值了 ...

  2. LaTeX竖立公式符号

    1.LaTeX技巧668:LaTeX如何实现直立积分号 \usepackage{amsmath,amssymb} \DeclareSymbolFont{EulerExtension}{U}{euex} ...

  3. Spring事物白话文

    脏读:一个事物读到了另外一个事物中尚未提交的数据: 幻读:A事物读到了B事物新增的数据:白话一点就是读到了别人insert的语句: 不可重复读:A事物读取了B事物更改的数据:白话一点就是我两次sele ...

  4. js -- 高阶函数的使用

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. C#常见几种集合比较

    1. ArrayList 1.1 ArrayList是一个特殊数组,通过添加和删除元素就可以动态改变数组的长度. ArrayList集合相对于数组的优点:支持自动改变大小,可以灵活的插入元素,可以灵活 ...

  6. CAN总线电平(隐性与显性)

            CAN2.0B规范定义了两种互补的逻辑数值:显性和隐性.同时传送显性和隐性位时,总线呈现显性状态:同时传送显性状态位时,总线呈现显性状态:同时传送隐性状态位时,总线呈现隐性状态.显性数 ...

  7. 在x64的Ubuntu系统下安装64bit的交叉编译工具aarch64-linux-gnu-gcc【转】

    sudo apt-cache search aarch64 查看哪些版本可以安装: sudo apt--aarch64-linux-gnu 安装一个gcc开头的5版本的支持64bit ARM linu ...

  8. 利用AJAX JAVA 通过Echarts实现豆瓣电影TOP250的数据可视化

    mysql表的结构   数据(数据是通过爬虫得来的,本篇文章不介绍怎么爬取数据,只介绍将数据库中的数据可视化):   下面就是写代码了: 首先看一下项目目录:   数据库层   业务逻辑层   pac ...

  9. 百炼OJ - 1002 - 方便记忆的电话号码

    题目链接 思路 开个一千万的数组计数,最后遍历即可. #include<stdio.h> #include<string.h> #include<algorithm> ...

  10. linux 网卡限速

    #安装git yum -y install git #下载wondershaper git clone  https://github.com/magnific0/wondershaper.git 第 ...