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. 【网站】i新媒上线了!

    [New]i新媒上线了! i新媒,是新媒体人常用和必备的工具导航,我们整合了自媒体平台.行业资讯.运营营销.学习创业等常用的网站,让新媒体人更快地获取有用的知识. 访问链接:https://ixm.h ...

  2. Android 开发 微信分享,登陆,获取信息

    1 获取appid和appsecret.        https://open.weixin.qq.com/cgi-bin/index?t=home/index&lang=zh_CN     ...

  3. 返回一条最近一次cURL操作明确的文本的错误信息。

    参考:https://www.runoob.com/php/func-curl_error.html <?php // 创建一个指向一个不存在的位置的cURL句柄 $ch = curl_init ...

  4. thinkphp中路由的基本使用

    1.在application中下的config.php中 以下代码改为true // 是否开启路由 'url_route_on' => true, // 是否强制使用路由 'url_route_ ...

  5. Docker - docker images存储位置,引出ls和du命令的不同

    docker镜像存储位置 docker info | grep "Docker Root Dir" 例如我的driver是overlay2,则docker镜像的实际存储在/var/ ...

  6. (GHRD)HPS

    DE1作为ARM+FPGA的组合,ARM和FPGA之间通信,两个区块间有三个通道可以让两部分实现传输数据,统称为 HPS-FPGA AXI Bridges. 分别为:FPGA-to-HPS Bridg ...

  7. 钉钉、钉应用(微应用和E应用)开发介绍

    钉钉,数字化新工作方式,让工作更简单 目前在钉钉的官网可以看到,超过700万家企业组织正在使用钉钉.笔者也相信,这一数字每天都在增加.获得群众的认可,也是理所当然的,体验过钉钉,就能感觉到,钉钉的考勤 ...

  8. 每天进步一点点------Allegro中SYMBOL种类

    Allegro 中SYMBOL 种类在Allegro 中, Symbol 有五种, 它们分别是Package Symbol .Mechanical Symbol.Format Symbol.Shape ...

  9. 每天进步一点点------创建Microblaze软核(二)

    第四步 进入Platform Studio操作界面通过向导创建软核后,进入到PlatformStudio——内核开发环境.Platform Studio主界面如下图. 在Ports项中,右键点击RS2 ...

  10. 微信小程序 购物车流程

    购物车流程 一.需求分析 a:全选,单选,根据选中的计算数目和总价 b:单个商品加减 c:删除一个商品 wxml 布局 <view> <view v-if="flag&qu ...