如何防止asp.net webform中的CSRF攻击?

问题描述 投票:0回答:2

如何防止 ASP.NET WebForms 中的CSRF跨站请求伪造)攻击?

ASP.NET MVC 中有类似

[ValidateAntiForgeryToken]
的东西吗?

webforms
2个回答
0
投票

当您谈论保护 ViewState 时,可以使用“ViewStateUserKey”。

基本上,您需要为每个用户使用一个特定的密钥,该密钥派生自 ASP.NET 会话。这是一个例子:

/// <summary>
///     Raises the <see cref="E:System.Web.UI.Control.Init" /> event to initialize the page.
/// </summary>
/// <param name="e">
///     An <see cref="T:System.EventArgs" /> that contains the event data.
/// </param>
protected override void OnInit(EventArgs e) {
    base.OnInit(e);

    // Validate whether ViewState contains the MAC fingerprint
    // Without a fingerprint, it's impossible to prevent CSRF.
    if (!Page.EnableViewStateMac) {
        throw new InvalidOperationException("The page does NOT have the MAC enabled and the view state is therefore vulnerable to tampering.");
    }

    ViewStateUserKey = Session.SessionID;
}

您可以了解更多信息,例如来自 Microsoft 文档


0
投票

ValidateAntiForgeryToken
而言,最简单的答案可能是

if (IsPostBack)
    AntiForgery.Validate();

如果不存在令牌,则会抛出异常。

可以在网络表单中添加令牌,如下所示:

<%= System.Web.Helpers.AntiForgery.GetHtml() %>

请注意,命名空间是

System.Web.Helpers
Nuget-Package 中的
Microsoft.AspNet.WebPages

以下是一些相关主题: CSRF 同步 ASP.net Web 表单应用程序中的令牌模式实现 以及 防止 ASP.NET Web 表单中的跨站点请求伪造 (csrf) 攻击

有关该主题的更多信息,使用 同步器令牌模式 (STP) 术语进行搜索可能会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.