Why Angular2 sanitize script tag in components?

2020-05-09 00:55发布

I totally understand that for security reasons and to prevent XSS attacks, user input must be sanitized: Sanitizing input from a text field or an input field.

But, I'm having a hard time trying to understand why Angular removes script elements from within a component template.

Like it's written in the official doc:

HTML, attributes, and binding expressions (but not the values bound) in templates are trusted to be safe

So if they are trusted to be safe why are script tags automatically removed when compiled?

I'm probably missing a security issue here, but even after reading docs about XSS I do not understand how a script tag within an Angular component's template that get compiled by the Angular compiler can compromise security.

Does anyone here have an answer to that?

1条回答
再贱就再见
2楼-- · 2020-05-09 01:32

Think about it this way: When you write an Angular template, the Angular compiler reads that template and creates an optimized javascript representation of what that template is doing and feeds that optimized javascript to the browser.

So, at the point when the browser gets a hold of your template, it's actually no longer HTML anymore - it's just javascript. So there's no support for dynamically loading external, unknown and potentially unsafe javascript from somewhere else at that point.

查看更多
登录 后发表回答