【问题标题】:CSRF fix in aspx page在 aspx 页面中的 CSRF 修复
【发布时间】:2018-08-13 20:44:37
【问题描述】:

我需要修复 aspx 页面的 CSRF 缺陷。代码是这样的-

ASPX -

<asp:Content runat='server'>
<asp:Panel runat='server'>
<table>
  <tr>
    <td>Username</td>
    <td><asp:TextBox runat="server" ID="Username" autocomplete="off"></asp:TextBox></td>
  </tr>
  <tr>
    <td>Password</td>
    <td><asp:TextBox runat="server" ID="Password" TextMode="Password" autocomplete="off"></asp:TextBox></td>
  </tr>
  <tr>
    <asp:Button ID="Submit" runat="server" Text="Submit"
                            OnClick="SubmitButton_Click" CssClass="Resizable" />
  </tr>
</table>
</asp:Panel>
</asp:Content>

ASPX.cs -

protected void SubmitButton_Click(object sender, EventArgs e)
        {
          //Code here
        }

现在在顶部插入 时会引发错误“服务器块格式不正确”。那么我应该如何进行修复。

【问题讨论】:

    标签: asp.net csrf antiforgerytoken


    【解决方案1】:

    您在此处使用网络表单。他们已经在母版页的模板中设置了 anti-xsrf(我认为它包含所有的视图状态数据)。

    因此,只要您使用的是母版页,就不必担心。

    如果您不使用母版页,只需使用会话状态、隐藏字段和 guid 构建您自己的页面。我从http://willseitz-code.blogspot.com/2013/06/cross-site-request-forgery-for-web-forms.html获取了以下内容

    你的隐藏域...

    <asp:HiddenField ID="antiforgery" runat="server"/>
    

    执行服务器端工作的代码...

    public static class AntiforgeryChecker
    {
        public static void Check(Page page, HiddenField antiforgery)
        {
            if (!page.IsPostBack)
            {
                Guid antiforgeryToken = Guid.NewGuid();
                page.Session["AntiforgeryToken"] = antiforgeryToken;
                antiforgery.Value = antiforgeryToken.ToString();
            }
            else
            {
                Guid stored = (Guid) page.Session["AntiforgeryToken"];
                Guid sent = new Guid(antiforgery.Value);
    
                if (sent != stored)
                {
                    throw new SecurityException("XSRF Attack Detected!");
                }
            }
        }
    }
    

    最后在您的 Page_Load 方法中的代码后面...

    AntiforgeryChecker.Check(this, antiforgery);
    

    【讨论】:

    • 错误 - AntiforgeryChecker.Check(this, antiforgery); 的当前上下文中不存在名称“antiforgery”;
    • @AnkurRai 你用runat='server'在页面上设置了隐藏字段吗?然后您应该能够在页面加载中引用它
    • 是的,我已经添加了。但是我得到了在配置中添加 SameSite 属性的替代解决方案。这行得通,减少混乱。
    • 您应该诚实地使用母版页。尝试重新发明轮子是没有意义的
    猜你喜欢
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    相关资源
    最近更新 更多