Reputation: 2095
Some time ago I've realized that I can't simply pass a string to a href parameter of an <img ...>
tag or background style. Only SafeUrl
and SafeStyle
instances are accepted. Frankly, I don't get the whole concept because I can sanitize any image URL or style by using a simple call. It could be reasonable if I could make a secure pipeline for marshalling safe image hrefs from a reliable backend API right to the View layer. Buf @angular/platform-browser
APIs can't be injected to a service, so I'm supposed to sanitize URLs in controls where I'm lacking any context which could help me to distinguish source reliability. Maybe I am missing something?
Upvotes: 4
Views: 843
Reputation: 9
The reason why the property binding works for the src attribute but not for the style property is because they have different security contexts in Angular.
The src attribute is considered to be a trusted URL context, which means that Angular automatically sanitizes the URL and marks it as safe to use in the src attribute of an img element.
On the other hand, the style property is considered to be an untrusted context, which means that Angular does not automatically sanitize any values that are set for this property. Instead, it expects the developer to manually sanitize the values using the DomSanitizer service.
One way to solve this issue is to use the DomSanitizer service to create a SafeStyle object from the SafeUrl object, in order to use it at [style] attribute property bidning
bypassSecurityTrustStyle method of the DomSanitizer service to create a SafeStyle object from the SafeUrl object.
Upvotes: 0
Reputation: 657198
Sanitizing means you explicitely tell Angular to consider the content safe. It is nothing more than a marker for Angular that you take responsibility and Angular doesn't need to check the content for potentially unsafe content. Only "sanitize" content where you know where it comes from and that it can't contain harmful content.
This is also why you need to bind it using property binding notation [innerHTML]="sanitizedConent
, because with innerHTML="{{sanitizedContent}}"
sanitizedContent
gets stringified (toString
called) and the marker gets lost in the process.
Upvotes: 5