0

I am trying to render the partial view from AJAX response in ASP.NET project with below code.

$.ajax({
     url: link,
     data: { ID: id }
 }).done(function (htmlResponse) {
     $('#div_id').html(htmlResponse); //Render partial view from ajax response.
});

I have performed the security scan for the application to find the vulnerabilities. After security scan we got the below message at $('#div_id').html(htmlResponse).

The application's }).done embeds untrusted data in the generated output with html, at line 26 of //partial.ascx. This untrusted data is embedded straight into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the output.

What is the best practice and how to avoid XSS attack and prevent embeds untrusted data in the generated partial view HTML from AJAX response

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Sarvesh
  • 64
  • 6
  • The vulnerability would need to be addressed (if it even exists, which it might not) in the code which generates the (partial) view, not in the code which appends that response to the page. The scanner doesn't really know the difference, it's just looking at where the output is injected into the page. But you probably don't want to HTML-encode *the entire output* here because presumably it contains markup and layout that you want on your page. The dynamic values used to generate that response, however, could contain malicious content, depending on how you're building it. – David Aug 23 '22 at 11:48
  • @David, Thank you for your comment. I am returning a partialview which contains html and script tags from Ajax call . Is there any approach to encode the partialview from server side and decode it from jQuery ajax response to update the DOM. if yes, give me the explanation with examples. – Sarvesh Aug 23 '22 at 14:24
  • If your plan is to HTML-decode the data before displaying it to the user then what is the purpose of HTML-encoding it in the first place? Do you want to HTML-encode *the entire response* before adding it to the page? That doesn't seem likely. Have you tested whether or not the framework is HTML-encoding dynamic values in the partial view already? The warning from the code scanning tool is providing you with a point to start investigating, there is no magic wand that will correct the issue in all cases. What has your investigation found? – David Aug 23 '22 at 14:32

0 Answers0