Junior — Middle
What methods of secure token storage in the browser can be used to prevent their disclosure?
sobes.tech AI
Answer from AI
To securely store tokens in the browser, it is important to minimize the risks of theft through XSS and other attacks. The main methods are:
- HttpOnly cookies: the token is stored in a cookie with the HttpOnly flag, which prevents access via JavaScript. This reduces the risk of theft through XSS.
- Secure cookies: the Secure flag ensures the cookie is only transmitted over HTTPS.
- SameSite cookies: restricts the sending of cookies only for requests from the same site, reducing the risk of CSRF.
- Storage in memory (e.g., in JavaScript variables): the token is not stored in localStorage or sessionStorage but kept in memory, which reduces the risk of long-term storage but requires re-authentication upon page refresh.
Example of setting an HttpOnly cookie in PHP:
setcookie('token', $jwtToken, [
'httponly' => true,
'secure' => true,
'samesite' => 'Strict',
'path' => '/',
'expires' => time() + 3600
]);
Thus, it is preferable to use HttpOnly and Secure cookies for storing tokens to prevent their disclosure through client-side scripts.