首页 > 解决方案 > ajax 响应返回 html 响应(XSS 验证码)

问题描述

function viewAcc() {
    var errorMsg = "";
    var result = true;
    $(".errorView").hide();
    var accNum = document.getElementById('custAccNum').value;
    var accType = document.getElementById('custAccType').value;
    $("#overlayPopup").show();
    $.ajax({
        url : '<attribute:resourceURL/>',
        data : {
            "custNo" : accNum ,
            "custType" : accType 
        },
        success : function(data) {
            if (data == 'CUS_ACC') {
                window.location = "/cust/account/c";
            } else {
                $("#overlayPopup").hide();
                //display warning
                $(".errorView").show();
                $(".errorView").html(data); // <--- XSS line
                e.preventDefault();
            }
        },
        cache : false,
        dataType : 'text',
        error : function(error, textStatus, errorThrown) {
            alert('error in ajax call: ' + textStatus);
            console.log('error in ajax call: ' + textStatus);
            window.location = "/cust/account/c/lookup";
        },
        timeout : ajaxTimeOutMilliSeconds
    });

}

所以veracode指出我有关于$(".errorView").html(data); 如何解决这个问题的问题?如果我只是将它变成文本,它会像 html 一样显示在客户端上吗?

标签: javascriptajaxxss

解决方案


您可以简单地使用.text()而不是.html(). 如果您没有来自服务器的任何标记,那么这是一个完全可行的替代方案,因为.text()将防止内容被解释为 HTML

//doing sc+ript is only needed here because Stack Snippets otherwise throws an error.
var msg = "This is <b>a message</b> with <script>console.log('some code')</sc"+"ript>";
$("#msgHtml").html(msg);
$("#msgText").text(msg);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

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


推荐阅读