防止用户注入HTML以编辑控制值 - 服务器端



我正在开发具有安全性的自定义控件。当用户无法访问控件时,该控件会使自己禁用,但也可以看不见。该控件没有渲染,并且不会出现在页面上。在这一点上,一切都很好。

我的问题是如何保护控件防止用户更改值?

我已经向Chrome HTML Inspector注入了我的表格输入价值属性。

public enum UserRole {
   Standard,
   Administrator,
   [...]
}
//For this example, my custom control is derived from HtmlInputText.  [ToolboxData("<{0}:MyCustomControl runat="server"></{0}:MyCustomControl>")]
public class MyCustomControl: System.Web.UI.HtmlControls.HtmlInputText
{
    public UserRole? MinimumRoleRequired { get; set; }
    protected override void OnLoad(EventArgs e)
    {
        //Simplified version
        if (this.Page.CurrentUser.Role < this.MinimumRoleRequired) 
        {
            this.Visible = false;
            this.Disabled = true;
            return;
        }
        [...]
    }
    protected override void Render(HtmlTextWriter writer)
    {
        if (!this.Visible || this.Disabled)
        {
            return;
        }
        [...]
    }
[...]
}
//My page who contain the control:
//HTML (MyPage.aspx)
<Controls:MyCustomControl ID="tbAdminOnly"runat="server"></Controls:MyCustomControl>

//C# (MyPage.aspx.cs)
public partial class UserEdit : Page
{
    protected override void OnInit(EventArgs e)
    {
       this.tbAdminOnly.MinimumRoleRequired = UserRole.Administrator;  
       [...]
    }
    protected override void OnLoad(EventArgs e)
    {
      base.OnLoad(e);
        if (this.IsPostBack)
        {
            string postBackValue = tbAdminOnly.Value;
            return;
        }
        tbAdminOnly.Value = "Hello world!";
    }
}

当我将页面加载为标准用户时,该控件不会渲染。但是,如果我在HTML页面中注入输入

//Note, i need to know the valid name/id but it could be done.
<input type="text" name="tbAdminOnly" id="tbAdminOnly" value="Damn shit">

现在,后背景是从注入的输入中的新值。我怎么能预防?

谢谢。

为了防止用户注入HTML控件,您需要对输入进行消毒。有类似的帖子。如何使用C#在HTML页面上消毒输入?

最新更新