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. 363. 矩形区域不超过 K 的最大数值和(利用前缀和转化为最大子序和问题)

    题目: 链接:https://leetcode-cn.com/problems/max-sum-of-rectangle-no-larger-than-k/ 给定一个非空二维矩阵 matrix 和一个 ...

  2. windows redis启动

    1.下载redis 2.启动redis 3.启动redis客户端并设置protected-mode为false

  3. C语言sprintf函数的深入理解

    由于sprintf跟printf在用法上几乎一样,只是打印的目的地不同而已,前者打印到字符串中,后者则直接在命令行上输出.这也导致sprintf比printf有用得多.所以本文着重介绍sprintf, ...

  4. 对象Bean与Map互转问题

    一.摘要 在实际开发过程中,经常碰到需要进行对象与map之间互转的问题,其实对于对象.Map 之间进行互转有很多种方式,下面我们一起来梳理一下: 利用 JSON 工具包,将对象转成字符串,之后再转成 ...

  5. Centos7添加软链接

    1.pycharm添加软连接: 命令行模式中输入命令: ln -s /root/pycharm-2018.1/bin/pycharm.sh /usr/bin/pycharm ps:代码中/root/p ...

  6. oracle 数据库手动备份和恢复

    一.备份命令: 1.cmd  : exp 2.cmd  :用户名/密码@ip地址/数据库名  如:     yyj/yyj@172.12.5.5/orcl    要导出的数据库 3.回车:输入要输出的 ...

  7. k线、指标绘制

    我接触的绘制有两种:gdi+和qt绘图.可以灵活的绘制任何想要的东西. 先上效果图吧. 如下:基于gdi+的股指和股票的绘制.上面是沪深成分股实时生成的股票指数走势,下面是IF主力走势和开平仓位置. ...

  8. 解决使用git出现 The file will have its original line endings in your working directory

    执行以下命令即可解决 git rm -r --cached . git config core.autocrlf false git add . . 代表当前目录

  9. VMware上Linux虚拟机和Windows共享文件夹

    参考文章:https://blog.csdn.net/qq_19004627/article/details/78689641 操作环境:主机:Windows10,VMware Workstation ...

  10. POJ 1330(LCA/倍增法模板)

    链接:http://poj.org/problem?id=1330 题意:q次询问求两个点u,v的LCA 思路:LCA模板题,首先找一下树的根,然后dfs预处理求LCA(u,v) AC代码: #inc ...