在我的javascript函数中,我使用了location.href,如下所示,它工作得很好,但是当我使用加强工具时,它显示了跨站脚本which can result in the browser executing malicious code.如何保护它免受跨站脚本攻击。非常感谢,您的回答将非常感谢。
发布于 2014-08-22 14:47:20
例如,当用户可以将数据放入网页或获取会话数据时,就会发生Cross-site Scripting。
如何保护
你永远不允许在你的网页中插入代码。
您不应该允许href更改页面内容。你总是在之前escape数据!
阅读这个关于location.href的答案:https://stackoverflow.com/a/24089350/2389232
示例
你有一个随GET变量变化的iframe:
sample.tld/index.jsp?iframe=none.jsp我可以向你的iframe注入一个script,所以你应该用转义字符来保护它:
// Escape the characters in the server and send it to the client.
// So the variable GET iframe will be valid发布于 2021-01-17 07:56:22
这段代码应该只在firefox中运行,因为并不是所有浏览器都实现了代理
您可以做的是用代理对象替换原始的location对象,在代理中添加一些逻辑来检查location的允许值。这不能防止对原始对象(location)的直接修改,但如果在代码中只使用代理对象,则应该没问题。
// suppose we are in example.com
let validator = {
set: function(obj, prop, val) {
if (prop === 'href') {
if(typeof val != 'string'){
throw new TypeError('href must be string.');
}
if (!val.startsWith("https://example.com/")) {
throw new Error('XSS');
}
}
obj[prop] = val;
return true;
},
get: function(obj, prop){
return prop in obj?
obj[prop] :
null;
}
};
let proxiedLocation = new Proxy(location, validator);
console.log(proxiedLocation.href);// work same as location.href
proxiedLocation.href = "https://example.com/page1";// work fine
proxiedLocation.href = "https://example.net/page1";// cause exceptionhttps://stackoverflow.com/questions/25440918
复制相似问题