1

I often use fromEvent method from RxJS. To be honest, I was expecting some magic from Angular, but apparently there is no. How can I prevent XSS attacks while using fromEvent?

Code example:

<input #myInput />

fromEvent(this.muInput.nativeElement, 'input').pipe(
  tap(inputEvent => this.saveToDatabase(inputEvent.data)
)
bigInt
  • 203
  • 5
  • 15
  • `fromEvent()` here has no significance to cross-site scripting. Same precautions when reading input directly from an `` element also apply here. See this [answer](https://stackoverflow.com/a/30882324/2924577) for preventing XSS. – Nikhil Oct 28 '19 at 15:40
  • Short answer, yes. – wentjun Oct 28 '19 at 15:47
  • The problem with using nativeDom event is you will lose reference from time to time – Fan Cheung Oct 29 '19 at 03:28
  • @Fan Cheung - can u elaborate a bit more? Never heard anything about this... – bigInt Oct 29 '19 at 07:38
  • Thanks for comments. I was expecting such answers, though had a dream Angular sanitizes bad vales for us. So edited question, maybe someone could answer it easier now. Thanks – bigInt Oct 29 '19 at 07:43

1 Answers1

1

To your question, use fromEvent you get the same output as valueChanges in reactive form, in terms of security measure, it is pretty much the same.

<input formcontrol="myInput"/>
myInput.valueChanges.subscribe(console.log) 

vs

<input #myInput />
fromEvent(this.muInput.nativeElement, 'input').subscribe(console.log)

Angular will sanitize the output if you wrap them in expressions curly brace in your view

{{ .. }} 

but it won't sanitize form input, so this is still a valid form input and sanitization still needs to be in place in the server side.

<script>alert('kdfkf')</script>

I won't recommend use fromEvent to handle changes as in most cases you only bind once to a certain element (supposingly in ngOnInit), if that element removed from DOM by*ngIf, your event is gone unless you have code to handle rebinding.

this answer might also help Need to insert Script tag in angular 2

as well as this https://angular.io/guide/security

Fan Cheung
  • 10,745
  • 3
  • 17
  • 39