Gartner has predicted that worldwide information security spending will witness a growth of 7% in 2017, with the total amount spent reaching close to $93 billion in 2018. This in...
By: Sheldon Fernandes | May 29, 2015
While working on a recent project, I needed to show the highlighting that was part of the Solr response. The highlighting was done with html markup as part of the response. When binding the response, it just printed out the html markup as basic text.
A little big of google-fu lead me to ng-bind-html and ng-bind-html-unsafe, tried both of these, but only in vein. Further research into the topic reviled that in order to allow us to use ng-bind-html, you have to use Strict Contextual Escaping which is a mode in which AngularJS requires bindings in certain contexts to result in a value that is marked as safe to use for that context. The was a newer implementation that is being used in newer version of Angular. In other words, it helps us to safely bind the values in our angular application.
Suppose we have the following code in our controller:
$scope.website = "<span style='background-color:yellow'>protein</span>";
In order for the highlighting to appear in the HTML code we have to tell angular that this piece of code is secure to bind. Using the method $sce.trustAsHtml() it converts the string to privileged one that is accepted and rendered safely by using the angular tag “ng-bind-html”.
Modified code from the controller:
var website = "<span style='background-color:yellow'>protein</span>"; $scope.trustedWebsite = $sce.trustAsHtml(website);
Why not disable SCE completely ?
One could, but it is strongly discouraged. SCE gives a lot of security benefits for just a little coding overhead. Taking an SCE disabled application and securing it would be a much bigger task than not disabling it and just using the code above for certain exceptions.