javascript - JS 阻止 XSS 但允许 HTML URL
问题描述
我有一个 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
正则表达式.com
推荐阅读
- python - 为什么可变内置对象不能在 Python 中进行哈希处理?这有什么好处?
- charts - 如何从详细记录上的字段创建垂直折线图
- typescript - 使用 fp-ts 重写一个用记录器包装的小函数
- python - 从 unstack() 到 Pandas 中的数据框
- c++ - 整数没有正确相加,但双打工作正常
- r - 有没有办法使用 R 根据关联来挑选数据?
- c# - 未读取数据库中的值
- javascript - Firestore 错误:“函数 Query.startAfter() 需要有效的第一个参数,但未定义。”
- php - 从需要/包含 PHP 文件中调用表单会导致白屏死机
- android - BottomSheet 中的 RecyclerView 未按预期工作