首页 > 解决方案 > JS 阻止 XSS 但允许 HTML URL

问题描述

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

用户可以输入完整的 url http://example.com,也可以在应用程序中输入路径/foo/barboo

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

是否可以对此输入进行编码,但仍允许将 url 视为这样?

标签: javascriptxss

解决方案


这是一个正则表达式,它将匹配以模式 (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

正则表达式.com


推荐阅读