How is concatenating urls in templates in angular less secure than in other locations?

后端 未结 2 1719
日久生厌
日久生厌 2021-01-01 21:52

I have an angularjs template which looks similar to this:


         


        
2条回答
  •  北海茫月
    2021-01-01 22:07

    This is called SCE (Strict Contextual Escaping): Like many "strictness" modes, this is configurable. But as of V 1.2 it is automatically set to true.

    More specifically, in contexts Angular considers to be vulnerable (like url's), there is less interpolation allowed (Strictness). Your URL concatenation is being "sanitized".

    You are already aware of the reason: XSS attacks. It's also used for the developer's protection: a slightly wrong url could cause data deletes or overwriting.

    You're probably confused why full string interpolation ng:src="{{fullUrl}}" is so much safer than string concatenation ng:src="/resources/{{id}}/thumbnail". TBH, I'm not sure there's a serious difference, but these are judgement calls.


    You have some alternatives for dealing with this annoyance:

    1) Wrap your url construction inside $sce.trustAs()

    
    

    2) You can disable SCE across your application, if you choose

    angular.module('myApp').config(function($sceProvider) {
        $sceProvider.enabled(false);
    });
    

    Correction:

    You can't call the $sce service from a directive. Only the $scope service is directly available. But you can use a function (or a directive that uses a function).

        $scope.createUrl = function (strName) {
            var truststring = '/resources/' + strName + '/thumbnail';
    
            return truststring;
        }
    

    and your directive call would look like

    
    

    In this case, if you wrap your concatenation in a function, you may not even need to de-sanitize it since you won't be breaking SCE rule.

提交回复
热议问题