Search code examples
angularsecurityescapingxsssanitization

To what degree do i have the worry about security (XSS) when handling user input in Angular?


To systematically block XSS bugs, Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.

Angular templates are the same as executable code: HTML, attributes, and binding expressions (but not the values bound) in templates are trusted to be safe. This means that applications must prevent values that an attacker can control from ever making it into the source code of a template. Never generate template source code by concatenating user input and templates. To prevent these vulnerabilities, use the offline template compiler, also known as template injection.

This is what Angular says about XSS. However it kinda seems that the first paragraph contradicts the second one (please correct me if i'm wrong). So my question is: Do i need to escape and sanitize my user input?


Solution

  • Code is trusted but values aren't. If you insert values using the normal Angular data binding, then they are encoded as appropriate, because Angular can recognize what is a value and what is code.

    For example, this doesn't require any additional escaping:

    <h1>Hello {{yourName}}!</h1>
    

    But if you tried to create a template using string concatenation. For example:

    '<h1>Hello ' + yourName + '!</h1>'
    

    or with a server-side language like PHP:

    <h1>Hello <?= $_GET['name'] ?> !</h1>
    

    Then Angular can't tell the difference between the literal html and the inserted value. Data inserted like this can now inject Javascript as well as Angular syntax.

    As long as you stick to the normal Angular mechanisms for inserting values, then you don't need additional encoding. The vulnerabilities come from bypassing angular and inserting values directly some other way.