nima ansari
nima ansari

Reputation: 582

How to prevent XSS attacks in ASP.NET Core Razor view?

In some part of my .cshtml file, I should render Html that users entered with Html-Editor.

My code is :

<div id="description">
    @Html.Raw(Model.Html)
<div>

but @Html.Raw() is not safe from XSS Attacks for example if user's entered Html content was something like this :

"<script>alert('XSS attack!')</script>"

this script run after entering this page!

how can I prevent from running these scripts(in general XSS attack) while rendering Html ?

Upvotes: 0

Views: 4334

Answers (1)

John H
John H

Reputation: 14655

You can encode the HTML before rendering it:

@Html.Raw(Html.Encode(Model.Html))

But this is the same as rendering it using:

@Model.Html

If you render the HTML, use view source, or your browser's inspector, and copy the generated script tag, you'll see it's been encoded:

&lt;script&gt;alert('XSS attack!')&lt;/script&gt;

But I personally prefer using the combination of Html.Raw and Html.Encode because it makes it clearer to the reader what the intent is.

Upvotes: 2

Related Questions