21

Angularjs 是否负责 XSS 攻击。我读过 ng-bind 会小心。但是当我尝试做一个示例来测试它时,它允许我使用 ng-model 在输入类型中插入 html 标签......它没有转义 Html 标签。

我的页面中有很多输入元素,它们与 ng-model 绑定,我应该怎么做才能确保如果我输入了 html 标签,angular 会忽略 html/scrip 标签。

前任。

<input id="name" ng-model="name"></input>

如果我输入为

'Hello, <b>World</b>!'

$scope.name 包含与我输入的内容相同的内容,但不排除标签。IE

  var val = $scope.name;
  console.log(val); 

打印一样

'Hello, <b>World</b>!'

请让我知道如何在 angularjs 中解决这个问题。

感谢

4

2 回答 2

28

看这里:http ://docs.angularjs.org/api/ngSanitize/service/$sanitize

如果你想转义使用ng-bind,它会呈现标签而不像这样解释:

Hello <b>World</b>不像Hello World

你明白吗 ?所以 ng-bind 是安全的,因为它不关心 HTML 标签。

如果您希望您的 HTML 标签被解释但安全地使用 ng-bind-html !

例如,如果您想显示此字符串:

'Hello <b>World</b><input type="text" />'

结果将是:Hello World但没有输入,因为 AngularJS 编译器使用 $sanitize 服务并检查 HTML 元素的白名单,并且 iput 未被授权。

也许 ng-bind-html 是您正在寻找的。

如果您只想确保用户不能在您的输入中放置 html 标签,只需在您的输入中使用指令 ng-pattern !

http://docs.angularjs.org/api/ng/directive/input

输入中允许的字符需要一个正则表达式!

希望能帮助到你 !

于 2014-04-11T09:03:52.120 回答
10

I don't believe that AngularJS has default whitelist input validation, which is what your test exercises. So a user can pretty much input anything they like. This is not surprising - whitelists are very domain specific, and Angular is a framework designed for a wide range of domains.

The main defense against XSS is to properly encode all untrusted data (see https://www.owasp.org/index.php/Top_10_2013-A3-Cross-Site_Scripting_(XSS)). This, Angular does by default.

Bottom line is that AngularJS is intended to be secure from XSS by default, no special action required. You can verify some basic scenarios by trying to output what you input into a view using the normal {{scopevariable}} notation.

I did find a detailed analysis of AngularJS XSS vulnerability: https://code.google.com/p/mustache-security/wiki/AngularJS. At the end of the comments, there is a link to a google doc with further discussion and response from the angular team.

于 2015-01-18T15:16:10.703 回答