过滤关键字防止XSS攻击

        public static string ClearXSS(string str)
        {
            string returnValue = str;
            if (string.IsNullOrEmpty(returnValue)) { return string.Empty; }

            ///过滤CSS Expression AND 过滤JavsScript
            returnValue = Regex.Replace(returnValue, @"<(style|script)[^<>]*?>.*?</(style|script)>", string.Empty, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Singleline);        

            ///过滤JS 事件 如:onclick="alert('123');"
            returnValue = Regex.Replace(returnValue, @"(?<=<[^>]+?)\b(onclick|ondatabinding|ondblclick|ondisposed|oninit|onkeydown|onkeypress|onkeyup|onload|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onprerender|onunload|onerror|onfocus)\b(?=.*?)", string.Empty, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Singleline);

            //过滤iframe|frame
            returnValue = Regex.Replace(returnValue, @"\<(iframe|frame)[^>]*>|<\/(iframe|frame)>", string.Empty, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Singleline);   

            return returnValue;
        }

 

posted on 2016-11-30 14:50  jianiu  阅读(2533)  评论(0编辑  收藏  举报