AngularJS 使用$sce控制代碼安全檢查


由於瀏覽器都有同源加載策略,不能加載不同域下的文件、也不能使用不合要求的協議比如file進行訪問。

在angularJs中為了避免安全漏洞,一些ng-src或者ng-include都會進行安全校驗,因此常常會遇到一個iframe中的ng-src無法使用

什么是SCE

SCE,即strict contextual escaping,我的理解是 嚴格的上下文隔離 ...翻譯的可能不准確,但是通過字面理解,應該是angularjs嚴格的控制上下文訪問。

由於angular默認是開啟SCE的,因此也就是說默認會決絕一些不安全的行為,比如你使用了某個第三方的腳本或者庫、加載了一段html等等。

這樣做確實是安全了,避免一些跨站XSS,但是有時候我們自己想要加載特定的文件,這時候怎么辦呢?

此時可以通過$sce服務把一些地址變成安全的、授權的鏈接...簡單地說,就像告訴門衛,這個陌生人其實是我的好朋友,很值得信賴,不必攔截它!

常用的方法有:

$sce.trustAs(type,name);
$sce.trustAsHtml(value); $sce.trustAsUrl(value); $sce.trustAsResourceUrl(value); $sce.trustAsJs(value);

其中后面的幾個都是基於第一個api使用的,比如trsutAsUrl其實調用的是trsutAs($sce.URL,"xxxx");

其中type可選的值為:

$sce.HTML
$sce.CSS
$sce.URL //a標簽中的href , img標簽中的src
$sce.RESOURCE_URL //ng-include,src或者ngSrc,比如iframe或者Object
$sce.JS

來自官網的例子:ng-bind-html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
</head>
<body ng-app="mySceApp">
    <div ng-controller="AppController">
      <i ng-bind-html="explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i>
    </div>
    <script type="text/javascript">
        angular.module('mySceApp',[])
        .controller('AppController', ['$scope', '$sce',
          function($scope, $sce) {
            $scope.explicitlyTrustedHtml = $sce.trustAsHtml(
                '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
                'sanitization.&quot;">Hover over this text.</span>');
          }]);
    </script>
</body>
</html>

實際工作中的例子:ng-src鏈接

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
</head>
<body ng-app="mySceApp">
<div ng-controller="AppController">
    <iframe width="100%" height="100%" seamless frameborder="0" ng-src="{{trustSrc}}"></iframe>
</div>
    <script type="text/javascript">
        angular.module('mySceApp',[])
        .controller('AppController', ['$scope','$sce',function($scope,$sce) {
            $scope.trustSrc = $sce.trustAs($sce.RESOURCE_URL,"http://fanyi.youdao.com/");
            // $scope.trustSrc = $sce.trustAsResourceUrl("http://fanyi.youdao.com/");//等同於這個方法
          }]);
    </script>
</body>
</html>

參考

【1】angular源碼分析:angular中入境檢察官$sce

【2】野獸的 Angular 學習 - - $sce 和 $sceDelegate

【3】$sce官方手冊


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM