【问题标题】:angularjs sanitize on ng-modelangularjs 对 ng-model 进行清理
【发布时间】:2016-01-20 20:53:39
【问题描述】:

我在服务器端使用 AntiXss 编码器进行 XSS 攻击,因此所有响应都包含 html 非转义字符,例如 "&lt:script&gt:alert(1);&lt:/script&gt:"(将 ';' 替换为 ' :')

在绑定时我使用 sanitize 和 ng-bind-html 没有问题。 更新模式还有另一个控制输入。当用户需要更新文本时,他们单击更新图标,然后我显示 textarea 并使用 ng-if 隐藏绑定标签。 textarea 具有 ng-model 属性。我无法像 ng-bind-html 这样在 textarea 上转义 html 字符,这是 sn-p 请帮助我变得疯狂..

小提琴;编辑模式 textarea 必须显示 "" 没有警报操作,并且将发送到服务器的数据也必须显示相同...

here is the fiddle

var app = angular.module('myApp',['ngSanitize']);

app.controller('MyCtrl', function($scope, $sce, $sanitize) {
    $scope.post1 = "<script>alert(1);</script>";
    //$scope.post2 = $sce.parseAsHtml("<h1>alert(1)</h1>");
    $scope.logs = ["log created"];
    $scope.log = function(val){
    	$scope.logs.push(val);
    }
});
.label {
  text-decoration:underline;
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-sanitize.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
      <div class="label">Edit mode :</div>
      <textarea ng-model="post1" style="width:100%;" rows="5"></textarea><br />
      <div class="label">Binding mode :</div>
      <div ng-bind-html="post1"></div><br />
      <div class="label">Data will be send to the server :</div>
      <div>{{post1}}</div><br />
      <div class="label">Logs (if needed) :</div>
      <div ng-repeat="d in logs">
        <p>{{($index+1) + ". " + d}}</p>
      </div>
</div>
</div>

【问题讨论】:

    标签: javascript angularjs angular-ngmodel angularjs-ng-model html-escape-characters


    【解决方案1】:

    您有 $sanitize 服务,但您似乎没有使用它。这个:

    $scope.post1 = "&amp;lt;script&amp;gt;alert(1);&amp;lt;/script&amp;gt;";

    应该是这样的:

    $scope.post1 = $sanitize("&amp;lt;script&amp;gt;alert(1);&amp;lt;/script&amp;gt;";)

    另外,$sanitize 不是核心 Angular 包的一部分。如果您还没有这样做,则需要包含 angular-sanitize.js 并添加对 ngSanitize 模块的依赖项: var app = angular.module('myApp', ["ngSanitize"]);

    【讨论】:

    • 我已经使用了 sanitize 并使用了 $sanitize 没有发生相同的事情:(
    • 我还可以确认使用 $sanitize 模块不适用于 ng-models
    猜你喜欢
    • 1970-01-01
    • 2013-04-04
    • 2017-11-19
    • 2017-04-13
    • 1970-01-01
    • 2014-10-04
    • 2017-03-17
    • 2013-03-13
    • 1970-01-01
    相关资源
    最近更新 更多