Store and display HTML string while avoiding JS, in ASP.Net Core 2

依然范特西╮ 提交于 2019-12-25 01:33:49

问题


I wish to store a formatted text using a Rich-Text editor (QuillJS) and while displaying back it should be rendered as HTML. By default the views encode the HTML to avoid JS Injection, and so the data is being treated as a plain string.

How do i manage to store and display / render the data as HTML, while at the same time filtering any JS in the string ?

I tried searching for api's but couldn't find any help. Secondly, these days it's getting increasing difficult getting to the documentation with just class name, hence full class name is highly appreciated in the answers.


回答1:


Assuming your model contains a public string MyHtml { get; set; } property, then to display the results in a view, use

@Html.Raw(Model.MyHtml)

To identify if the posted value contains any <script> tags and/or to remove them from the value, use a html parser such as Html Agility Pack. For example in your POST method, you could add a ModelStateError and return the view

public ActionResult Save(MyModel model)
{
    if (HasScripts(model.MyHtml)
    {
        ModelState.AddModelError("MyHtml", "The html cannot contain script tags");
    }
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    // save and redirect
}

Where HasScripts() is

public bool HasScripts(string html)
{
    HtmlDocument document = new HtmlDocument();
    document.LoadHtml(html);
    HtmlNode root = document.DocumentNode;
    return root.Descendants("script").Any();
}

Alternatively, if you want to just remove them before saving, you could use the following method

public string RemoveScripts(string html)
{
    HtmlDocument document = new HtmlDocument();
    document.LoadHtml(html);
    HtmlNode root = document.DocumentNode;
    IEnumerable<HtmlNode> scripts = root.Descendants("script");
    for(int i = 0; i < scripts.Count(); i++)
    {
        HtmlNode script = scripts[i];
        script.Remove();
    }
    return scripts.Any() ? document.ToString() : html;
}

and use it as

model.MyHtml = RemoveScripts(model.MyHtml);

Note: If you are tempted to use a regex for this, I recommend reading Regular Expression for Extracting Script Tags.

You might also want to consider checking for other potentially malicious elements such as <embed>, <iframe>, <form> etc




回答2:


Do not use @Html.Raw(...). Users can perform Javascript injections. There exists many libraries to prevent JS injections. I have used AntiXSS to display HTML.

AntiXSS: https://www.nuget.org/packages/AntiXSS/



来源:https://stackoverflow.com/questions/50503360/store-and-display-html-string-while-avoiding-js-in-asp-net-core-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!