How to prevent XSS (Cross Site Scripting) whilst allowing HTML input

前端 未结 5 1764
梦如初夏
梦如初夏 2020-12-06 11:23

I have a website that allows to enter HTML through a TinyMCE rich editor control. It\'s purpose is to allow users to format text using HTML.

This user entered conten

5条回答
  •  一整个雨季
    2020-12-06 11:45

    I try to replace tag element format like this:

    public class Utility
    {
        public static string PreventXSS(string sInput) {
            if (sInput == null)
                return string.Empty;
            string sResult = string.Empty;
            sResult = Regex.Replace(sInput, "<", "< ");
            sResult = Regex.Replace(sResult, @"<\s*", "< ");
            return sResult;
        }
    }
    

    Usage before save to db:

        string sResultNoXSS = Utility.PreventXSS(varName)
    

    I have test that I have input data like :

    
    

    it will be run on browser. After I add Anti XSS the code above will be:

    < script>alert('hello XSS')< /script>
    

    (There is a space after <)

    And the result, the script won't be run on browser.

提交回复
热议问题