Why Cookie is preferable compared to localStorage when it comes to authentication ? (2024)

Why Cookie is preferable compared to localStorage when it comes to authentication? (1)

Why Cookie is preferable compared to localStorage when it comes to authentication? (2)

Published in

·

2 min read

·

Dec 21, 2022

--

Why Cookie is preferable compared to localStorage when it comes to authentication? (3)

We know about JWT, or JSON Web Token, as an industry standard RFC 7519 method for representing claims securely between two parties. JWT is very common nowadays. But where should we store them in the front end?

In this article, I will break down 2 common places to store tokens. Cookies and LocalStorage

Local Storage

To use localStorage, just simply call use the localStorage object

localStorage.setItem("yourTokenName", yourToken)
localStorage.getItem("yourTokenName", yourToken)

Pros:

  • Very convenient, don’t need any backend, just pure JavaScript.
  • Big Data size, about 5mb.

Cons:

  • Vulnerable to XSS attacks. An XSS attack happens when an attacker can can take the access token that you stored in your localStorage because they can run JavaScript on your website.

Cookies

To set cookie , we can do:

document.cookie = "cookieName=value"

or do this with http request:

Set-Cookie: <cookie-name>=<cookie-value>

Pros:

  • If you’re using httpOnly and secure cookies this means that your cookies cannot be accessed using JavaScript so even if an attacker can run JS on your site, they can't read your access token from the cookie.
  • Can set expiration date

Cons:

  • Only 4kb of storage

XSS Attacks

Like I said above, local storage is vulnerable because it’s easily accessible using JavaScript and an attacker can retrieve your access token. However, while httpOnly cookies are not accessible using JavaScript, this doesn't mean that by using cookies you are safe from XSS attacks involving your access token.

If an attacker can run JavaScript in your application, they can just send an HTTP request to your server which will automatically include your cookies; It’s just less convenient for the attacker because they can’t read the content of the token although they might don’t have to.

CSRF Attacks

Cross-site request forgery (also known as CSRF) is a web security vulnerability that allows an attacker to induce users to perform actions that they do not intend to perform.

However, this can be mitigated easily using sameSite flag in your cookie by including an anti-CSRF token.

Cookies still have some vulnerabilities but it’s preferable compared to localStorage whenever possible. Because:

  • Both localStorage and cookies are vulnerable to XSS attacks, but it's harder for the attacker to do the attack when you're using httpOnly cookies.
  • Cookies are vulnerable to CSRF attacks, but it can be mitigated using sameSite flag and anti-CSRF tokens.
  • You can still make it work, even if you need to use the Authorization: Bearer header or your JWT is larger than 4KB.
Why Cookie is preferable compared to localStorage when it comes to authentication ? (2024)

FAQs

Why Cookie is preferable compared to localStorage when it comes to authentication ? ›

Because: Both localStorage and cookies are vulnerable to XSS attacks, but it's harder for the attacker to do the attack when you're using httpOnly cookies. Cookies are vulnerable to CSRF attacks, but it can be mitigated using sameSite flag and anti-CSRF tokens.

Why would you use a cookie instead of local storage? ›

If you have small amounts of data to store, such as user preferences or language settings, it's better to use cookies due to their small storage capacity. Average to large data size. If you have big amounts of data to store, use local storage or session storage, depending on the data persistence.

Why are cookies used for authentication? ›

Cookies are pieces of data used to identify the user and their preferences. The browser returns the cookie to the server every time the page is requested. Specific cookies like HTTP cookies are used to perform cookie-based authentication to maintain the session for each user.

Which has more advantages as compared to cookie authentication? ›

Session tokens have some advantages over cookies. They are more secure, as they are not exposed to XSS or CSRF attacks and can be encrypted or signed.

What are the differences between cookie local storage and session storage? ›

To be more specific, local Storage stores up to 10 megabytes and session storage stores up to 5 megabytes. On the other hand, these provide a very restrictive and small storage capacity of 4 kilobytes. So we cannot store large amounts of information in cookies.

Top Articles
Cash Flow Statement (CFS)
Was ist der Cashflow und wie wird er berechnet?
11 beste sites voor Word-labelsjablonen (2024) [GRATIS]
Ffxiv Act Plugin
Toa Guide Osrs
Netr Aerial Viewer
Television Archive News Search Service
Lorton Transfer Station
Online Reading Resources for Students & Teachers | Raz-Kids
Flixtor The Meg
Doublelist Paducah Ky
Trade Chart Dave Richard
Riegler &amp; Partner Holding GmbH auf LinkedIn: Wie schätzen Sie die Entwicklung der Wohnraumschaffung und Bauwirtschaft…
CSC error CS0006: Metadata file 'SonarAnalyzer.dll' could not be found
Magic Mike's Last Dance Showtimes Near Marcus Cedar Creek Cinema
Carter Joseph Hopf
Med First James City
O'reilly's Auto Parts Closest To My Location
Google Feud Unblocked 6969
Directions To 401 East Chestnut Street Louisville Kentucky
[Birthday Column] Celebrating Sarada's Birthday on 3/31! Looking Back on the Successor to the Uchiha Legacy Who Dreams of Becoming Hokage! | NARUTO OFFICIAL SITE (NARUTO & BORUTO)
Epro Warrant Search
Walmart stores in 6 states no longer provide single-use bags at checkout: Which states are next?
The Grand Canyon main water line has broken dozens of times. Why is it getting a major fix only now?
Mail.zsthost Change Password
Happy Life 365, Kelly Weekers | 9789021569444 | Boeken | bol
Exl8000 Generator Battery
Certain Red Dye Nyt Crossword
Shadbase Get Out Of Jail
Prey For The Devil Showtimes Near Ontario Luxe Reel Theatre
Cornedbeefapproved
Waters Funeral Home Vandalia Obituaries
Evil Dead Rise Ending Explained
Ullu Coupon Code
Generator Supercenter Heartland
Skepticalpickle Leak
Wcostream Attack On Titan
Hotels Near New Life Plastic Surgery
Chuze Fitness La Verne Reviews
Woodman's Carpentersville Gas Price
Marcus Roberts 1040 Answers
18 terrible things that happened on Friday the 13th
Mid America Clinical Labs Appointments
Levi Ackerman Tattoo Ideas
How I Passed the AZ-900 Microsoft Azure Fundamentals Exam
6576771660
Makes A Successful Catch Maybe Crossword Clue
9:00 A.m. Cdt
18 Seriously Good Camping Meals (healthy, easy, minimal prep! )
Hampton Inn Corbin Ky Bed Bugs
Mast Greenhouse Windsor Mo
Latest Posts
Article information

Author: Aracelis Kilback

Last Updated:

Views: 5770

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Aracelis Kilback

Birthday: 1994-11-22

Address: Apt. 895 30151 Green Plain, Lake Mariela, RI 98141

Phone: +5992291857476

Job: Legal Officer

Hobby: LARPing, role-playing games, Slacklining, Reading, Inline skating, Brazilian jiu-jitsu, Dance

Introduction: My name is Aracelis Kilback, I am a nice, gentle, agreeable, joyous, attractive, combative, gifted person who loves writing and wants to share my knowledge and understanding with you.