我有一个登录页面 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/