首页 文章

ng-non-bindable仅用于元素的内容

提问于
浏览
1

在我们的Angular应用程序中,我们有一个链接,在服务器端填充了用户内容 . 因此,我们需要告诉Angular不要解释该链接内容 . 否则,如果用户或攻击者在其中放置Angular绑定表达式(比如说{}),那么Angular会对其进行评估,从而打开一个安全漏洞 - 一种XSS攻击 .

ng-non-bindable大多数都这样做 . 但是,我们还希望链接本身可以被Angular操纵 .

<a href="" class="side-bar-element" ng-class="{ 'side-bar-element-selected': isSiteSelected(@site.value.ID) }">@site.value.Name</a>

@ site.value.Name是插入内容的服务器端代码 .

如果我们将ng-non-bindable放在a元素上,那么ng-class将不起作用 . 我能看到的唯一解决方案是在其中插入另一个span / div并将ng-non-bindable应用于:

<a href="" class="side-bar-element" ng-class="{ 'side-bar-element-selected': isSiteSelected(@site.value.ID) }"><span ng-non-bindable>@site.value.Name</span></a>

这看起来很笨拙,不得不修改HTML结构只是为了阻止Angular干扰服务器端数据 .

有没有更清洁的解决方案?

理想情况下,我希望ng-non-bindable(或变体)表示“不绑定内容,但将此元素视为正常” .

1 回答

  • 0

    如果用户或攻击者将Angular绑定表达式放入用户内容(比如{}),那么Angular会对其进行评估,从而打开一个安全漏洞 - 一种XSS攻击 .

    使用 $delegate 服务降低 ng-non-bindable 指令优先级:

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <body ng-app="nonBindableExample">  
      <script>
        function delegator($delegate)
         {
         /* Override the directive definition object (DDO) */ 
         $delegate[0].priority = 0;
         
         return $delegate;
         }
    
    
        function provider($provide)
         {
         /* Decorate ng-non-bindable with a proxy function */
         $provide.decorator('ngNonBindableDirective', ["$delegate", delegator]);
         }
    
        /* Inject the provider and the delegator methods with services */
        provider['$inject'] = ['$provide'];
        delegator['$inject'] = ['$delegate'];
    
        /* Inject the module with the new provider */
        angular.module('nonBindableExample', []);
        angular.module("nonBindableExample").config(["$provide",provider]);
      </script>
      
    <div>{{$id}}</div><div ng-non-bindable class="{{$id}}">{{$id}}</div></div>
    </body>
    

    如果在单个DOM元素上定义了多个指令,有时需要指定应用指令的顺序 . 优先级用于在调用编译函数之前对指令进行排序 . 优先级定义为数字 . 首先编译具有更高数字优先级的指令 . 预链接功能也按优先级顺序运行,但后链接功能以相反的顺序运行 . 具有相同优先级的指令的顺序是未定义的 . 默认优先级为0 .

    或者只需通过 <script type="text/ng-template"> 分隔用户内容:

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
      <!--Declare module-->
      <script>
      angular.module('foo', []);
      </script>
    
    <!--Auto Bootstrapping-->
    <div ng-app="foo">  
      <!--Inline Template-->
      <script type="text/ng-template" id="baz">
        <span ng-non-bindable>Hi {{bar}}</span>
      </script>
    
      <!--data binding-->
      <a href="" ng-init="bar=1" ng-class="{{bar}}" ng-include="'baz'"></a>
    </div>
    

    a 元素使用 ng-include 指令,并使用带有 ng-non-bindable 指令的 span 元素将文本与元素分离 .

    References

相关问题