gpt4 book ai didi

javascript - JS 防止 XSS 但允许 HTML URL

转载 作者:行者123 更新时间:2023-11-29 20:53:14 29 4
gpt4 key购买 nike

我有一个 Angular 1 应用程序,带有用于创建网站通知的表单输入。

用户可以输入完整的 url http://example.com 或者他们也可以输入应用程序内的路径 /foo/barboo

但是,攻击者也可以输入 javascript:alert(1);//,当按下通知链接时,JS 将触发。

是否可以对这个输入进行编码,但仍然允许 url 被这样对待?

最佳答案

这是一个正则表达式,它将匹配以架构 (http/https/ftp) 开头的 URI 和以斜杠开头的“相对”URI:

/((\/[\w-.]+)(\/[\w-.]+)*\/?)|(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?)/gi

const re = /((\/[\w-.]+)(\/[\w-.]+)*\/?)|(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?)/gi

console.log("https://example.com/foo/bar".match(re)[0]); //matches

console.log("/foo/bar/baz/bim".match(re)[0]); //matches

console.log("javascript:alert('xss');//".match(re)); //doesn't match (null)

console.log("/foo/bar/baz/bim.html".match(re)[0]); //matches

console.log("https://example.com/foo/bar-api.php?e=mc2".match(re)[0]); //matches

regexr.com

关于javascript - JS 防止 XSS 但允许 HTML URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50677210/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com