Avoiding cross-site scripting vulnerabilities, an AJAX response will return an HTML response

function accessAccount() {
    var errorMessage = "";
    var checkedResult = true;
    $(".errorDisplay").hide();
    var accountNumber = document.getElementById('customerAccountNumber').value;
    var accountType = document.getElementById('customerAccountType').value;
    $("#overlayPopup").show();
    $.ajax({
        url : '<attribute:resourceURL/>',
        data : {
            "number" : accountNumber ,
            "type" : accountType 
        },
        success : function(response) {
            if (response == 'CUSTOMER_ACCOUNT') {
                window.location = "/customer/account";
            } else {
                $("#overlayPopup").hide();
                //display warning
                $(".errorDisplay").show();
                $(".errorDisplay").text(response); // <--- Sanitize this line for XSS
                e.preventDefault();
            }
        },
        cache : false,
        dataType : 'text',
        error : function(error, textStatus, errorThrown) {
            alert('Error: ' + textStatus);
            console.log('Error: ' + textStatus);
            window.location = "/customer/account/lookup";
        },
        timeout : ajaxTimeOutMilliSeconds
    });

}

The Veracode report indicates an issue with $(".errorView").html(data);. How can I address this? Will simply changing it to text prevent client-side rendering of HTML?

Answer №1

Avoid placing full confidence in tools that suggest you are susceptible to XSS attacks.

The true vulnerability to XSS arises when the content of data cannot be relied upon. Given that this data originates from your own server, it should have been properly sanitized for any potential XSS vulnerabilities before being included in the response to the Ajax request.

Answer №2

Instead of using .text(), you can simply utilize .html(). When there is no server-side markup involved, this alternative is perfectly suitable as .text() prevents the content from being interpreted as HTML.

//The script tag is necessary in this example to prevent errors in Stack Snippets.
var message = "This is <b>a message</b> with <script>console.log('some code')</sc"+"ript>";
$("#messageHtml").html(message);
$("#messageText").text(message);


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h3>Message via .html():</h3>
<div id="messageHtml"></div>

<h3>Message via .text():</h3>
<div id="messageText"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is Optional Chaining supported by Next.js on Vercel?

While Next.js does support Optional Chaining, I have encountered an issue when trying to deploy the following code snippet: module.exports = { experimental: { outputStandalone: true, }, images: { domains: process.env.NEXT_PUBLIC_IMAGE_DOMAINS ...

underscore.js provides _.where utility for filtering arrays of strings and objects

I am looking to verify whether a specific string is present in a collection of objects. The variable this.props.value contains the string "apple, peach" and this.state.list consists of a list of objects with key-value pairs. My goal is to determine if "ap ...

Why is the "&" symbol in my JSON showing as "&amp;" when displayed in an Angular view?

In my project, I am utilizing a json file to store key/strings for localization with angular-translate. One of the strings in this file is 'Profile & Preferences', which I am using in my view. However, when I use ng-bind-html to display this ...

Using JavaScript to utilize a variable containing a .match method with Regex Expression

Recently, I started delving into the world of regex with the aim of incorporating variables in my matches. Imagine I have a string that reads "Total: $168" My goal is to extract just the numerical value; 168. This is what I currently have: totalCost = t ...

Using arrow functions in Typescript e6 allows for the utilization of Array.groupBy

I'm attempting to transform a method into a generic method for use with arrow functions in JavaScript, but I'm struggling to determine the correct way to do so. groupBy: <Map>(predicate: (item: T) => Map[]) => Map[]; Array.prototype ...

NextJs's React-Quill is unable to effectively highlight syntax using the highlightJS library

I have been working on a NextJs application (blog) that utilizes react-quill as a rich text-editor. As part of my setup, I am making use of the Next custom 'app' feature, where my UserProvider component wraps everything to provide global access t ...

What is the most effective method for synchronizing data with HTML5 video playback?

I am currently developing a program that retrieves data from an android application and plays it back on a web browser. The android app allows users to record videos while logging data every 100ms, such as GPS location, speed, and accelerometer readings, i ...

Having trouble with input functionality on iPad due to a CSS, LI, div, or clipping issue?

https://i.sstatic.net/muMSG.png One challenge I am facing is related to several inputs housed within an LI and div that are sortable using jQuery. The problem arises specifically on the iPad when attempting to click into the inputs to enter information - ...

Sending a string to the server-side using Jquery Ajax

Is there a way to send variable data to the server side? I am looking for a solution. $("form").submit(function () { GetSelectedValues(); }); function GetSelectedValues() { var data = $("#DDL_WorkCategory").val(); } This ...

What could be the reason for my mongoose model failing to save in mongodb?

I am experiencing an issue with my simple Post model and route for creating posts. After submitting a new post using Postman, the request hangs for a moment before returning an error in JSON format. The model data is never saved successfully. Below is the ...

Issue with Laravel 5.4: AJAX behaving unexpectedly and not returning errors as it should

After going through several tutorials on handling AJAX requests in Laravel, I'm still facing some issues. Each tutorial has its own approach... Finally, one method is not giving me a 500 error, but it's not displaying validation errors as expect ...

Tips on expanding the dimensions and incorporating more members in a radar graph's Chartjs tag

I need to make some adjustments to the font size and color in a radar chart. Specifically, I want to change the name on the side of each data point. I have already tried adjusting the legend labels using the following code: options={{ ...

Laravel throws an error message "expression expected" when trying to use the @

I keep encountering an issue when attempting to pass a variable from PHP code to JavaScript. Expression expected Here is the code snippet I am using in Laravel 7.0 : <script> let variable = @json($array); </script> Although the code still ...

Having trouble exporting a static HTML file using Next.js

https://i.stack.imgur.com/xQj7q.pngI'm a beginner in the world of React. Recently, I completed a project where I utilized "next build && next export" in my package.json file for static HTML export. By running the npm run build command, an out folder w ...

Move a pin on Mapbox

I have a question regarding my map markers: https://i.sstatic.net/2HndV.png Currently, the center of the blue markers align with my desired coordinates. Is there a way to adjust the markers slightly upwards so that the tip sits exactly on my specified po ...

Is it feasible to develop a functional computer interface using threejs?

Is it feasible to integrate a window into threejs that could facilitate the use of standard desktop applications (such as code editors) within the virtual scene? Please note: This is being implemented within a custom application or a node-webkit environme ...

Passing a text via ajax to the controller yielding a null response

Currently, I have a dropdown menu that loops through an enum list. When an option is selected, it sends the enum as a string (as 'this'). Then, to retrieve the string value of that object, I proceed to get the value. Here is what it looks like: ...

MVC - experiencing a catastrophic failure when attempting to post model data to the controller using ajax

Here's what I'm attempting to achieve: This is my viewmodel structure: public class Inputs { public string UserName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddr ...

Develop an Engaging JavaScript Quiz with Elements That are Generated Dynamically

** Need help setting answer values for checkboxes Currently, I have a code that displays (2) questions with (4) possible answers each. Next to each answer is a checkbox with a default value of false. However, I want to link the value of each checkbox to ...

Multiple Ajax(Jquery method) Submissions with just one click and issue with Image not being sent to the server

Having trouble submitting form data to the server after client-side validation using jQuery. I've been working on this all day and could really use some help. I created a jQuery slider for my login form, where it slides to the next input field after v ...