Home > Software engineering >  Javascript : using LocalsStorage is unsafe, I want to know why?
Javascript : using LocalsStorage is unsafe, I want to know why?

Time:11-30

Many resources on the internet claim LocalStorage can be unsafe as app can be prone to cross site scripting attack. If that is the case what is the safest way to store Authenticaton token, I understand cookie is another option but is it safe or not?

CodePudding user response:

What they probably mean by this is that if your website falls victim to an XSS attack, the attacker can extract the tokens of your users from localStorage, because they are inherently accessible to scripts.

The same applies to most cookies, however you can set cookies to not be available to scripts, so that they are only used for sending back to the server (where the server checks them and handles auth). That way, an XSS attack cannot extract cookies that have the HttpOnly flag set from your users browsers.

While at it, also set the Secure flag of your cookie so that it is only ever transmitted over an encrypted connection.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#restrict_access_to_cookies

https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#security

https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#define_where_cookies_are_sent

In PHP 7.3 and up for example, you would use the setcookie function like this to set a Secure, HttpOnly, SameSite cookie for authentication:

setcookie("__Host-Auth-Cookie", "123-session-id", [
    'expires' => time()   12 * 60 * 60,
    'path' => '/',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax',
]);

CodePudding user response:

Cookies are usually safe as they are just there to understand you better. But some malicious websites send you cookies in the hope of getting your pc infected with a virus or some other malware. My recommendation is that if the website you are on is seemingly looking trustable and is from a known organization then you are good to go

  • Related