关于 xss 和 csrf 的文章似乎有误

Article about xss and csrf seems wrong

我在网上找到这篇关于 xss 和 csrf 的文章 https://www.redotheweb.com/2015/11/09/api-security.html 当您一直向下滚动到 'the solution' 时,它告诉您使用令牌和会话 cookie。下面是一段示例代码。我的问题是,当发生 xss 攻击时,所谓的黑客可能只是 运行 那段代码。从本地存储中检索令牌,cookie 将自动附加。还是我遗漏了什么?

authenticate(login, password)
    .then(function(authentication) {
        window.sessionStorage.setItem('token', authentication.token); // store token
    })
    .then(getAccounts)
    .then(function(accounts) {
        // display the accounts page
        // ...
    })
    .catch(function(error) {
        // display error message in the login form
        // ...
    });

/**
 * @return {Promise}
 */
function getAccounts() {
    return fetch('https://api.bobank.com/accounts', {
        headers: {
            'Authorization': 'Token ' + window.sessionStorage.getItem('token'), // <= include token
            'Content-Type': 'application/json; charset=utf-8',
            'Accept': 'application/json',
        },
        credentials: 'include' // <= include session cookie
    }).then(function(response) {
        return response.json();
    })
}

我的具体问题是这篇文章是否有误。是否有解决此问题的安全方法。

是的,XSS 攻击通常可以做其余代码可以做的任何事情。认为 XSS 需要窃取令牌或会话 cookie 才能成功是一种常见的误解。如果您容易受到 XSS 攻击,那么 XSS 可以(正如您所指出的)简单地执行相同的代码,从而实现 CSRF。