I need help on how to add sanitization to the url and alt text of this code. What is the best way to do this as this is something I'm not very familiar with. I tried researching but not able to find a clear answer. I added DomSanitizer to typescript for the src but not sure if this is correct and I don't know what to use for alt
angular/html
<sdps-card-image src={{cardData.image?.url}} alt={{cardData.image?.altText}} is-
responsive="true">
</sdps-card>
ts
import { Component,Input } from '@angular/core';
import { Card } from "../../models/card.model";
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'app-card',
templateUrl: './card.component.html',
})
export class CardComponent {
@Input() cardData = new Card();
constructor(private sanitizer: DomSanitizer) {}
transform(value: string) {
return (this.sanitizer.bypassSecurityTrustResourceUrl(value));
}
}
Any assistance would be appreciated on how to get the correct code to fix this would be appreciated.
It seems your code does the opposite of what you intended.
bypassSecurityTrust*
methods should be invoked only if you do NOT want to sanitize the DOM injected values because you trust that they are safe.In most cases, there is no need to explicitly perform sanitization because Angular does it by default (effectively treating injected values as untrusted by default).
To test the need for explicit sanitization, you could set
cardData.image.url
to"javascript:alert('Injecting malware')"
.If Angular automatic sanitization succeeds, you should see a warning in the console (in development mode) and the URL will then be rewritten to
"unsafe:javascript:alert('Injecting malware')"
which will not run in the browser. If you see the alert, then you will need to do the sanitization yourself by invokingDomSanitizer.sanitize
. (Except that in the case of an image URL, thejavascript
URL scheme is not recognized anyway so you would see a console error instead).When sanitizing values explicitly, you also need to specify the correct security context.
I see that you tried to use the sanitizer in a
transform
method which looks like an implementation ofPipeTransform
interface. That code will not even run actually. There are multiple locations that could work depending on your codebase. If you need to invokeDomSanitizer.sanitize
, I think it is better to do it early when you initialize the cardData object or when you setcardData.image.url
.Lastly, I'd like to mention that you can use property binding instead of interpolation. You can rewrite your code like this:
Replace
src={{cardData.image?.url}}
with[src]="cardData.image?.url"