web123456

How does Vue's text interpolation and Attribute binding prevent XSS?

Hello classmate, I am Dad Mu. Welcome to like, collect, comment and follow.

existVueIn this article, text interpolation and Attribute binding are two common ways to display dynamic content. Today we will take a look at how Vue can ensure the application.Security, prevent cross-site scripting attacks (XSS).

Text interpolation

Text interpolation in Vue through double curly braces{{ }}Syntax implementation allows you to bind data to HTMLtemplatethe text position in. For example:

<span>{{ message }}</span>
  • 1

whenmessageWhen the value of the variable changes, Vue will automatically update the DOM to reflect the new value. However, ifmessageVariables contain content input by users, and these contents may become the carrier of XSS attacks without proper processing.
How to ensure safety in Vue? In fact, whether using templates or renderingfunction, the content will be automatically escaped. For example, message contains the following script:

'<script>alert("You're attacked")</script>'
  • 1

Then it will be escaped as:

&lt;script&gt;alert(&quot;You were attacked&quot;)&lt;/script&gt;
  • 1

Therefore script injection is avoided. The escape is through suchtextContentThe browser native API is completed, so unless there is a security vulnerability in the browser itself, there will be no security vulnerability.

Attribute binding

Vue also supports itv-bindDirective (or its abbreviation:) to bind the properties of HTML elements. For example:

<h1 v-bind:title="message">
  hello
</h1>
  • 1
  • 2
  • 3

Like text interpolation, dynamic attribute bindings are automatically escaped. If the message contains:

'" οnclick="alert(\'You were attacked\')'
  • 1

Then it will be escaped to the following HTML:

&quot; οnclick=&quot;alert('You're attacked')
  • 1

Therefore, it avoids closuretitleattribute and inject new arbitrary HTML. The escape is through suchsetAttributeThe browser native API is completed, so unless there is a security vulnerability in the browser itself, there will be no security vulnerability.

in conclusion

I don’t know if you have found that Vue did nothing when dealing with security issues of text interpolation and Attribute binding, but just used the browser native API:textContentandsetAttributeThe built-in escape function is done, and a statement is also issued that "unless there is a security vulnerability in the browser itself, there will be no security vulnerability."

Okay, the sharing is over, thank you for your likes, see you next time.