1. In the first place, tokens are not designed to protect against XSS, but CSRF.

2. The reason for CSRF attack is that the browser automatically carries cookies, but the browser does not automatically carry tokens.

Two typical types of cyber attacks

XSS: Users inject malicious code into other users’ pages in various ways. You can use scripts to get information, make requests, things like that.

CSRF: Cross-site request attack, simply put, is the attacker through some technical means to trick the user’s browser to visit a previously authenticated website and perform some operations (such as sending emails, sending messages, or even property operations such as transferring money or buying goods). Because the browser has been authenticated, the site being visited will act as if it were a genuine user action. This exploits a flaw in user authentication on the Web: simple authentication can only guarantee that a request is sent from a user’s browser, but not that the request itself is voluntarily made by the user. CSRF doesn’t get any information about the user, it just tricks the user’s browser into acting on their behalf.

Cookie: the user clicks the link, but the cookie is not invalid. As a result, the back end thinks that it is the user’s normal operation after the request is initiated, and then deducts the payment.

Cookie: after login, the backend generates a sessionID and returns it to the client in the cookie, and the server always records the sessionID. The client will bring the sessionID with each request later, and the server uses the sessionID to verify the identity and other operations. So somebody else gets a cookie and they get a sessionid and they can completely replace you.

Token: When the user clicks the link, the browser will not automatically carry the token. Therefore, even if the request is sent, the token verification on the back end will not pass, so the payment will not be deducted

Token: After login, the backend does not return a token to the client, the client stores the token, and each time the client requests the developer to manually bring the token in the header, and the server only needs to verify the token each time to use the information in the token for the next operation.

This is my personal understanding of why only cookies are hijacked but not tokens.