问题描述
我使用 ng-bind-html 来防止跨站脚本,阅读 sanitize 并找到 此讨论 和 另一个很好的讨论.
虽然,我没有为我工作,你能帮我找出原因吗?
HTML:
JS:
$scope.to_trusted = function(html_code) {返回 $sce.trustAsHtml(html_code);};
当我添加以下行时
并将其添加到消息中,我可以看到它在 DOM 中呈现,当我刷新页面时,我可以看到消息.
并显示弹出窗口:
你能告诉我我做错了什么吗?
首先,它本身并不是 XSS.
其次,$sce.trustAsHtml
与您的想法完全相反——事实上,它指示 Angular相信"HTML 是安全的——而不是清理.
要清理,您需要将 ngSanitize
作为依赖项添加到您的应用程序,并将 ng-bind-html
直接添加到 html_code
(没有to_trusted
).
angular.module("myApp", ["ngSanitize"]).controller("MainCtrl", function($scope){$scope.html_code = '<img src="x" onerror="alert(\'cross\')">';});
在 HTML 中:
I used ng-bind-html in order to prevent cross site scripting,read about sanitize and found this discussion and another good discussion.
Although, i did't work for me, can you please help me in figure out why?
HTML:
<p class="big-text" ng-bind-html="to_trusted(message)">
JS:
$scope.to_trusted = function(html_code) {
return $sce.trustAsHtml(html_code);
};
when i'm adding the following line
<img src="x" onerror="alert('cross')">
and adding it to a message i can see it rendered in the DOM, and when i'm refreshing the page i can see the message.
and the popup is shown:
can you please tell me what am i doing wrong?
First of all, it's not XSS on its own.
Second, $sce.trustAsHtml
does exactly the opposite of what you thought - it, in fact, instructs Angular to "trust" that the HTML is safe - not to sanitize.
To sanitize, you need to add ngSanitize
as a dependency to your app, and ng-bind-html
directly to html_code
(without to_trusted
).
angular.module("myApp", ["ngSanitize"])
.controller("MainCtrl", function($scope){
$scope.html_code = '<img src="x" onerror="alert(\'cross\')">';
});
And in the HTML:
<div ng-bind-html="html_code"></div>
这篇关于ng-bind-html 不会阻止跨站点脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!