使用AngularJS中的SCE来防止XSS攻击的方法(2)

<script type="text/javascript"> angular.module('HelloApp', ["ngSanitize"]) .controller('HelloCtrl', ['$scope', '$sce', function($scope, $sce){ $scope.name=""; $scope.processHtmlCode = function() { $scope.helloMessage = "<h1>" + $scope.name + "</h1>"; $scope.trustedMessage = $sce.trustAsHtml( $scope.name ); } }]) </script> <!-- Pay attention to class hello which is coded in UI and as a result, element is painted in red--> <div> <span><strong>ng-bind directive: Note that HTML text is entered as it is.</strong></span><br/> <span ng-bind="helloMessage">{{helloMessage}}</span> </div> <hr/> <div> <span>Note that script tag is executed as well.</span> <span ng-bind-html="trustedMessage"></span> </div>

下面的图片展示了当在文本域中输入将要被插入DOM中的HTML样式代码时,会是什么样子. 这里的结果就是, 其它的HTML元素也带上了红色, 如下所示. 在某些场景中,黑客可能会插入一段带有背景样式越苏,这可能会显示出原本不要被显示的背景,给最终用户带来糟糕的体验.

2015618103229268.png (1024×254)

 

<html> <head> <title>Hello AngularJS</title> <link type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular-sanitize.min.js"></script> </head> <body ng-app="HelloApp" ng-controller="HelloCtrl"> <div> <form> <h1>AngularJS XSS Demo Test</h1> <hr/> <div> <input type="text" ng-model="name" ng-change="processHtmlCode()" placeholder="Enter Some HTML Text..."/> </div> </form> <hr/> </div> <hr/> <div> <span><strong>ng-bind directive: Note that HTML text is entered as it is.</strong></span><br/> <span ng-bind="helloMessage">{{helloMessage}}</span> </div> <hr/> <div> <span>Note that script tag is executed as well.</span> <span ng-bind-html="trustedMessage"></span> </div> <hr/> <div> <span>ng-bind-html directive: Note that image is displayed appropriately as a result of text entered in the text field.</span> <span ng-bind-html="helloMessage"></span> </div> <hr/> <script type="text/javascript"> angular.module('HelloApp', ["ngSanitize"]) .controller('HelloCtrl', ['$scope', '$sce', function($scope, $sce){ $scope.name=""; $scope.processHtmlCode = function() { $scope.helloMessage = "<h1>" + $scope.name + "</h1>"; $scope.trustedMessage = $sce.trustAsHtml( $scope.name ); } }]) </script> </body> </html>

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgdxzs.html