javascript - 在通过 JavaScript 的 location.replace() 导航之前确保 URL 是相对的

标签 javascript url xss

我有一个登录页面 https://example.com/login#destination 其中 destination 是用户在需要时尝试导航到的目标 URL登录。
(即 https://example.com/destination)

我考虑使用的 JavaScript 是

function onSuccessfulLogin() {
    location.replace(location.hash.substring(1) || 'default')
}
  • 这会导致 XSS 漏洞,由攻击者提供链接
    https://example.com/login#javascript:..

  • 我还需要防止在登录后导航到相似的网站。
    https://example.com/login#https://looks-like-example.com
    https://example.com/login#//looks-like-example.com

如何调整 onSuccessfulLogin 以确保散列 # 部分中提供的 URL 是相对 URL,而不是以 javascript: 开头、https:// 或任何其他绝对导航方案?

一种想法是评估 URL,并在导航之前查看 location.origin 是否保持不变。您能否建议如何执行此操作或更好的方法?

最佳答案

来自 OWASP 关于 Preventing Unvalidated Redirects and Forwards 的建议:

It is recommended that any such destination input be mapped to a value, rather than the actual URL or portion of the URL, and that server side code translate this value to the target URL.

因此,一种安全的方法是将一些键映射到实际的 URL:

// https://example.com/login#destination

var keyToUrl = {
  destination: 'https://example.com/destination',
  defaults: 'https://example.com/default'
};

function onSuccessfulLogin() {
  var hash = location.hash.substring(1);
  var url = keyToUrl[hash] || keyToUrl.defaults;

  location.replace(url);
}

您还可以考虑仅提供 URL 的路径部分并在代码中附加主机名:

// https://example.com/login#destination

function onSuccessfulLogin() {
  var path = location.hash.substring(1);
  var url = 'https://example.com/' + path;

  location.replace(url);
}

不过我会坚持映射。

关于javascript - 在通过 JavaScript 的 location.replace() 导航之前确保 URL 是相对的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37531263/

相关文章:

javascript - 在 JavaScript 中如何检测天气类型是 Array 还是 Object?

php - 从 HTML 表单到 PHP 页面的 URL 链接

javascript - Angular - 如何防止 RxJs fromEvent 中的 XSS 攻击?

xss - 谁能告诉我为什么/如何这个 XSS 向量在浏览器中工作?

javascript - 禁用 div 中的所有 javascript

javascript - JS如何隐藏页面的所有分类

javascript - 添加到 Safari 中的收藏夹/书签栏 (CMD +D)

javascript - javascript 中的函数用括号括起来

magento - magento 站点中不同 url 键中的重复内容

html - 当url中有空格时htaccess重定向