2

I am trying to figure out how DomSanitizer really works in Angular 10.

I've been trying to sanitize the following CSS string without any luck:

const testString = 'transform: rotate(70deg);color: blue;';
const result = this.sanitizer.sanitize(SecurityContext.STYLE, testString);

In the code snippet above, the result constant variable is always equal to testString. What I expect to happen is: result should only contain color: blue; and the transform CSS property is filtered out from the string.

I have also tried to sanitize some JavaScript code, provided through a string like the following:

const testString = 'alert("hacked!");console.log("logged");';
const result = this.sanitizer.sanitize(SecurityContext.SCRIPT, testString);

However, in this example, the sanitize() function throws an error with the message unsafe value used in a script context.

What I expected to happen here is: result constant variable should be an empty string.

Peter
  • 33
  • 4
  • It doesn't filter out the dangerous part(s). You'll have to wrap it in a try/catch block and handle it yourself. – Chrillewoodz Jul 18 '21 at 08:10
  • Then what is the point of this function if it doesn't actually sanitize anything - is the idea to just bypass Angular's built-in protection mechanisms? As far as I'm aware, functions like `bypassSecurityTrustHtml` are designed for that purpose - the `sanitize` function should actually sanitize input, no ? – Peter Jul 19 '21 at 20:26
  • I think the point is just to protect you from any dangerous snippets of code. When a dangerous snippet is found, it's up to you to decide how you want to handle it. Idk what you're doing exactly but maybe you can add validation for when your snippets are created instead to see that it's actually valid? – Chrillewoodz Jul 20 '21 at 07:00

1 Answers1

0

You can place if Logic to check if its blue - and then else to return nothing or the desired data in return.

if(testString==='blue'){
const result = this.sanitizer.sanitize(SecurityContext.STYLE, testString);

} else {
console.log('whatever you like')
}
chris burd
  • 728
  • 3
  • 9
  • I don't really understand how this helps my case. I'm expecting a certain output but not getting it and I can't figure out why - I've combed through the official documentation but the description for SecurityContext and its various options is sparse, to say the least. – Peter Jul 19 '21 at 20:29
  • its to sanitize the style of the color blue and make sure its blue - which is what you asked for. – chris burd Jul 19 '21 at 21:26