处理asp.net的MVC JavaScript注入 [英] handle javascript injection in asp.net mvc

查看:194
本文介绍了处理asp.net的MVC JavaScript注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何处理JavaScript注入在asp.net的MVC(C#)应用程序?

How can we handle the javascript injection in asp.net mvc (C#) application?

我可以在视图中使用Html.En code。但问题是,我有HTML也像一个博客帖子的页面显示。

I can use Html.Encode in my View. But the problem is i have html also to show in the page like a blog post.

我需要删除的应用程序的输入元素进入脚本?我该怎么做,在一个共同的地方?

I need to remove the script entered in the input elements of the application? How can i do that in a common place?

推荐答案

高级别这样做的最好的做法是:

The "high-level" best practice for doing this is:


  • 存储用户输入它被输入到系统中的方式

  • HTML EN code所有的用户输入时,它是任何页
  • 在输出
  • 使用白名单的方式去恩code允许的HTML字符,属性,属性值,等你带在previous一步codeD

HTML编码输出用户输入将会从您的网站上执行的JavaScript停止

HTML Encoding user-input on output will stop JavaScript from being executed on your site.

为什么要存储用户输入作为进入的原因是因为你可能会在未来决定在其他格式不具备相同的输出用户数据(PDF,电子邮件,JavaScript中,RSS等)规则编码。因此,你应该让数据尽可能接近其原始形式越好。这将使事情变得更容易应对更高版本。

The reasons why you want to store user-input "as entered" is because you may in the future decide to output user data in other formats (PDF, email, JavaScript, RSS, etc) that don't have the same rules for encoding. As a result, you should keep data as close to its original form as possible. This will make things easier to deal with later.

有关HTML编码用户输入时,可以使用 System.Web.HttpUtility.HtmlEn code(...)

For HTML Encoding user-input, you can use System.Web.HttpUtility.HtmlEncode(...).

要合并步骤2及3,你可以使用微软的 AntiXSS库。它提供了一些额外的编码方法,该HttpUtility类不提供,让您的工作更轻松。我不知道,直到马尔科姆评论中指出,此库的最新版本包含一个名为 GetSafeHtmlFragment(...)方法,它将手动删除所有的JavaScript。这将处理所有为你删除用户输入的JavaScript code的繁重的工作。您很可能希望使用 GetSafeHtmlFragment 不可以 GetSafeHtml ,其目的是EN code整个HTML文档。

To combine steps 2 & 3, you can use Microsoft's AntiXSS library. It provides some extra encoding methods that the HttpUtility class doesn't provide to make your job easier. I was unaware until Malcolm pointed out in the comments, that the latest version of this library includes a method called GetSafeHtmlFragment(...) which will remove all JavaScript manually. This will handle all of the heavy lifting of removing user-entered JavaScript code for you. You will most likely want to use GetSafeHtmlFragment and not GetSafeHtml, which is designed to encode entire HTML documents.

小提示:阅读最新AntiXss发布的意见(2012年1月在写这篇的时间),如果你发现你期待的功能不能正常工作。您可能要考虑使用根据您的需要旧版本,但注意,旧版本中他们已经知道的安全缺陷。 微软已经承认这个问题,并正在研究解决方案。

Minor note: Read the reviews of the latest AntiXss release (January 2012 at the time of writing this) if you find functionality is not working as you expect. You may want to consider using an older release depending on your needs, though be advised that older releases have known security defects in them. Microsoft has acknowledged the issue and is looking into a solution.

这篇关于处理asp.net的MVC JavaScript注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆