ASP.NET CSRF 解决【网摘】
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 解决【网摘】的更多相关文章
- Delphi 中DataSnap技术网摘
Delphi2010中DataSnap技术网摘 一.为DataSnap系统服务程序添加描述 这几天一直在研究Delphi 2010的DataSnap,感觉功能真是很强大,现在足有理由证明Delphi7 ...
- Feedly订阅Blog部落格RSS网摘 - Blog透视镜
网络信息爆炸的时代,如何更有效率地阅读文章,订阅RSS网摘,可以快速地浏览文章标题,当对某些文章有兴趣时,才点下连结连到原网站,阅读更详细的文章,Feedly Reader阅读器除了提供在线版订阅RS ...
- Bloglines订阅Blog部落格RSS网摘 - Blog透视镜
网络信息蓬勃发展,Blog部落格越来越普及,如果逐一地去浏览网站,势必费时费力,倘若信息可以自己送上门,那就可以节省不少时间,就好像看报纸的标题,有兴趣才点连结,进到网站浏览文章内容,Blogline ...
- TCP/IP协议头部结构体(网摘小结)(转)
源:TCP/IP协议头部结构体(网摘小结) TCP/IP协议头部结构体(转) 网络协议结构体定义 // i386 is little_endian. #ifndef LITTLE_ENDIAN #de ...
- Vim命令快捷键(网摘)
Vim命令快捷键(网摘) 原文出处:[?---->home]
- c#与C++类型转换网摘
转载自 C++和C#转换 https://www.cnblogs.com/zjoch/p/4147182.html c#与C++类型转换,网摘 //c++:HANDLE(void *) ...
- ubuntu解决网易云无法打开
最近首次入手ubuntu18 摸索了很久,当然网易云是不可缺少的一部分,在配置好各种环境+程序后,也找到了解决网易云的方法了. 首先安装好网易云 默认情况下需要在终端使用 sudo 才能运行 解决的办 ...
- Python入门及容易!网摘分享给大家!
Python:Python学习总结 背景 PHP的$和->让人输入的手疼(PHP确实非常简洁和强大,适合WEB编程),Ruby的#.@.@@也好不到哪里(OO人员最该学习的一门语言). Pyth ...
- 采访ServiceStack的项目领导Demis Bellot——第1部分(网摘)
ServiceStack是一个开源的.支持.NET与Mono平台的REST Web Services框架.InfoQ有幸与Demis Bellot深入地讨论了这个项目.在这篇两部分报道的第1部分中,我 ...
随机推荐
- linux 关键字搜索文件
在www目录下查找包含关键字’summer’,且后缀名为php文件的操作命令 find /www/ -name '*.php' |xargs grep '/Summer'
- 0003 配置完整的url访问路径
本文本以OrgsAndUser APP为例,每增加一个url都需要做以下步骤: 1 创建模板 在OrgsAndUsers/Templates目录下创建一个名为org-home.html的文件,内容如下 ...
- 十分钟理解JavaScript引擎的执行机制
关注专栏写文章 十分钟理解JavaScript引擎的执行机制 方伟景 千锋前端开发推动市场提升的学习研究者. 4 人赞同了该文章 首先,请牢记2点: JS是单线程语言 JS的Event Loop是JS ...
- Python学习笔记9——异常处理
处理异常 如果执行到程序中某处抛出了异常,程序就会被终止并退出.你可能会问,那有没有什么办法可以不终止程序,让其照样运行下去呢?答案当然是肯定的,这也就是我们所说的异常处理,通常使用 try 和 ex ...
- JMeter CSRFToken认证登陆(正则提取器的使用)
转自:http://blog.csdn.net/lion19930924/article/details/51189210 前几天用JMeter模拟登陆,但是这个网站开启了csrf认证,因此在post ...
- bootstrap4的改进
- html div四边阴影效果
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or ...
- hadoop cdh 的那些坑 第二弹
卧槽 ....一直连不上datanode 不知道为什么数据节点一直连接不上.. 2019-07-19 16:10:00,156 INFO org.apache.hadoop.ipc.Client: R ...
- 慎用--skip-grant-tables命令
该命令作用是跳过授权表,也就是说谁都能进入mysql看到所有数据表,输入任意字符账号密码都可以 当忘记账号密码时可以使用改命令修改密码,但是要随用随关,重启mysql,不然服务器上会有很大的风险. 介 ...
- django 0
web 框架的本质 - socket服务端 socket 收发消息 根据不同的路径返回不同的内容 模板渲染 jinja2 字符串替换 mvc model(模型/db) view(展示html) con ...