asp.net-mvc 在 WebForms 中生成 AntiForgeryToken
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1321508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating AntiForgeryToken in WebForms
提问by Naz
I have a .NET Webforms site thanks needs to post to my MVC Application which currently sits inside the Webform site as a separate application.
我有一个 .NET Webforms 站点,感谢需要发布到我的 MVC 应用程序,该应用程序目前作为一个单独的应用程序位于 Webform 站点内。
The Webform application need to POST some sensitive values to the MVC Application.
Webform 应用程序需要向 MVC 应用程序发布一些敏感值。
Is there a way to generate a AntiForgeryToken() in my WebForms Application so it can be passed with the form post.
有没有办法在我的 WebForms 应用程序中生成 AntiForgeryToken() 以便它可以与表单帖子一起传递。
Otherwise does anyone know of any other custom anti forgery code that will allow me to do something similar to the MVC's AntiForgeryValidation.
否则,是否有人知道任何其他自定义反伪造代码,这些代码将允许我执行类似于 MVC 的 AntiForgeryValidation 的操作。
回答by Ian Ippolito
This is an old question, but the latest Visual Studio 2012 ASP.NET template for web forms includes anti CSRF code baked into the master page. If you don't have the templates, here's the code it generates:
这是一个老问题,但用于 Web 表单的最新 Visual Studio 2012 ASP.NET 模板包含嵌入母版页的反 CSRF 代码。如果您没有模板,下面是它生成的代码:
Protected Sub Page_Init(sender As Object, e As System.EventArgs)
' The code below helps to protect against XSRF attacks
Dim requestCookie As HttpCookie = Request.Cookies(AntiXsrfTokenKey)
Dim requestCookieGuidValue As Guid
If ((Not requestCookie Is 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 As HttpCookie = New HttpCookie(AntiXsrfTokenKey) With {.HttpOnly = True, .Value = _antiXsrfTokenValue}
If (FormsAuthentication.RequireSSL And Request.IsSecureConnection) Then
responseCookie.Secure = True
End If
Response.Cookies.Set(responseCookie)
End If
AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
End Sub
Private Sub master_Page_PreLoad(sender As Object, e As System.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 (Not DirectCast(ViewState(AntiXsrfTokenKey), String) = _antiXsrfTokenValue _
Or Not 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
回答by Richard
Implementing it yourself is not too difficult.
自己实现并不太难。
- Generate a GUID
- Put it in a hidden field
- Also put it in Session or Cookie (in the latter case, with some anti-tamper protection)
- At the start of processing the form compare the field and stored token.
- 生成 GUID
- 把它放在一个隐藏的领域
- 也把它放在 Session 或 Cookie 中(在后一种情况下,有一些防篡改保护)
- 在开始处理表单时,比较字段和存储的令牌。
(If you look at the implementation of MVC, there is very little more to it. A few helper methods is all you need.)
(如果您查看 MVC 的实现,就会发现它的内容很少。您只需要一些辅助方法。)
回答by DavidC
The C# version of Ian Ippolito answer here:
Ian Ippolito 的 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)
{
// The code below helps to protect against XSRF attacks
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
// 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;
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
HttpOnly = true,
Value = _antiXsrfTokenValue
};
if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
{
responseCookie.Secure = true;
}
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
}
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.");
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
回答by Mark Brackett
WebForms has a pretty similar analog in Page.ViewStateUserKey. By setting that to a per-user value(most choose HttpSessionState.SessionId), WebForms will validate the ViewState1as part of the MAC check.
WebForms 在Page.ViewStateUserKey 中有一个非常相似的模拟。通过将其设置为每个用户的值(大多数选择HttpSessionState.SessionId),WebForms 将验证 ViewState 1作为MAC 检查的一部分。
overrides OnInit(EventArgs e) {
base.OnInit(e);
ViewStateUserKey = Session.SessionId;
}
1There are scenarios where ViewStateUserKey will nothelp. Mainly, they boil down to doing dangerous things with GET requests (or in Page_Load without checking IsPostback), or disabling ViewStateMAC.
1有场景中ViewStateUserKey会不会帮助。主要是,它们归结为使用 GET 请求(或在没有检查 IsPostback 的情况下在 Page_Load 中)做危险的事情,或者禁用 ViewStateMAC。
回答by Keith
You can use reflection to get at the MVC methods used to set the cookie and matching form input used for the MVC validation. That way you can have an MVC action with [AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]attributes that you can post to from a WebForms generated page.
您可以使用反射来获取用于设置 cookie 和用于 MVC 验证的匹配表单输入的 MVC 方法。这样,您就可以拥有一个带有[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]属性的 MVC 操作,您可以从 WebForms 生成的页面发布这些属性。
See this answer: Using an MVC HtmlHelper from a WebForm
请参阅此答案:使用 WebForm 中的 MVC HtmlHelper

