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

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

在angularJs中爲了避免安全漏洞,一些ng-src或者ng-include都會進行安全校驗,因此常常會遇到一個iframe中的ng-src無法使用。[轉載自http://www.cnblogs.com/xing901022/p/5100551.html]

什麼是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 οnmοuseοver="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>
發佈了21 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章