ElementRef security risk angular 2

前端 未结 1 513
野性不改
野性不改 2020-12-17 19:10

Why ElementRef is not secure to use if so, what we can use instead?

I\'m been using this ElementRef to see or watch a specific html tag and then to send as specific

相关标签:
1条回答
  • 2020-12-17 19:48

    Using ElementRef doesn't directly make your site less secure. The Angular team is just saying "Hey, you may use this, just be careful with it".

    If you are only using an ElementRef to get information, like in your example a certain width, there is no security risk involved at all. It's a different story when you use an ElementRef to modify the DOM. There, potential threats can arise. Such an example could be:

    @ViewChild('myIdentifier')
    myIdentifier: ElementRef
    
    ngAfterViewInit() {
      this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;
    }
    

    The problem with this is that it gets inserted directly into the DOM, skipping the Angular sanitisation mechanisms. What are sanitisation mechanisms? Usually, if something in the DOM is changed via Angular, Angular makes sure it's nothing dangerous. However, when using ElementRef to insert something into the DOM, Angular can't guarantee this. So it becomes your responsibility that nothing bad enters the DOM when using ElementRef. An important keyword here is XSS (Cross-Site Scripting).

    To summarise: If you poll the DOM for information, you are safe. If you modify the DOM using ElementRef, make sure the modifications don't possibly contain malicious code.

    0 讨论(0)
提交回复
热议问题