DEV Community

Rajat Sharma
Rajat Sharma

Posted on

Understanding Sessions and Tokens: A Deep Dive

When building modern web applications, managing authentication is one of the most crucial aspects. Two major approaches are used for authentication:

  • Session-based authentication
  • Token-based authentication

In this article, we’ll explore these concepts in detail and understand how they relate to Local Storage, Access Tokens, and Refresh Tokens.


πŸ”‘ What is a Session?

A session is a way to maintain user authentication by storing session data on the server. When a user logs in, the server creates a session and assigns it a unique Session ID. This ID is stored in a cookie and sent with each request, allowing the server to recognize the user.

πŸ›  How Session-based Authentication Works

  1. User logs in β†’ Credentials (username & password) are sent to the server.
  2. Server validates β†’ If correct, the server creates a session and generates a Session ID.
  3. Session storage β†’ The Session ID is stored in a cookie (HttpOnly & Secure recommended).
  4. Requests include the session β†’ Every request contains the session ID, allowing the server to authenticate the user.
  5. Session expiration β†’ The session expires after a set time or when the user logs out.

🚨 Drawbacks of Session-based Authentication

  • Requires server-side storage, leading to scalability issues.
  • Works best for monolithic applications but is not ideal for microservices or APIs.
  • Can be vulnerable to Session Hijacking if cookies are not properly secured.

πŸ”‘ What is a Token?

A token is a self-contained, stateless authentication mechanism that allows authentication without requiring server-side session storage.

The most common format is JWT (JSON Web Token), which contains encoded user information, expiration time, and a signature for verification.

πŸ›  How Token-based Authentication Works

  1. User logs in β†’ Credentials are sent to the server.
  2. Server validates β†’ If correct, the server generates a JWT (Access Token) and returns it to the client.
  3. Client stores the token β†’ The token is stored in Local Storage, Session Storage, or HTTP-only Cookies.
  4. Requests include the token β†’ The client includes the token in the Authorization header (Bearer <token>).
  5. Server validates the token β†’ The server verifies the token’s signature and extracts the user information.
  6. Token expiration β†’ Once expired, a Refresh Token is used to get a new Access Token.

βœ… Advantages of Token-based Authentication

  • Stateless β†’ No need to store sessions on the server, making it scalable.
  • Secure β†’ Can be signed & encrypted.
  • Ideal for APIs β†’ Works well with SPAs (React, Vue, Angular) and microservices.

πŸ“Œ Access Token vs. Refresh Token

πŸ”Ή Access Token

  • Short-lived (e.g., 15 minutes to 1 hour).
  • Sent with every request in the Authorization header.
  • Used to authenticate users in APIs.

πŸ”Ή Refresh Token

  • Long-lived (e.g., 7 days to 30 days).
  • Stored securely (e.g., HTTP-only Cookies).
  • Used to obtain a new Access Token without re-authenticating.

πŸ›  How Refresh Tokens Work

  1. The Access Token expires after a short time.
  2. The client sends a Refresh Token to the server.
  3. The server validates the Refresh Token.
  4. If valid, a new Access Token is issued.
  5. If expired or invalid, the user must log in again.

πŸ“‚ Where to Store Tokens?

1️⃣ Local Storage (window.localStorage)

βœ… Pros:

  • Persistent (survives page reloads).
  • Easy to use.

❌ Cons:

  • Vulnerable to XSS attacks.
  • Cannot be accessed by HttpOnly flags.

2️⃣ Session Storage (window.sessionStorage)

βœ… Pros:

  • Accessible only within the session.
  • Clears when the tab is closed.

❌ Cons:

  • Vulnerable to XSS attacks.
  • Does not persist across sessions.

3️⃣ HTTP-only Cookies (Set-Cookie header)

βœ… Pros:

  • Not accessible by JavaScript (protected from XSS).
  • Automatically included in every request.

❌ Cons:

  • Vulnerable to CSRF attacks if not properly secured.
  • Requires additional security measures like SameSite, Secure, HttpOnly flags.

πŸ†š Session vs. Token Authentication

Feature Session-based Authentication Token-based Authentication
Storage Server-side Client-side (JWT, Tokens)
Scalability Less scalable Highly scalable
Security Risks Session Hijacking XSS, CSRF attacks
Best for Monolithic apps SPAs, Mobile, APIs

πŸ” Best Practices for Secure Authentication

  • Use HTTP-only cookies for storing Refresh Tokens.
  • Set expiration time on Access Tokens and Refresh Tokens.
  • Implement CSRF protection when using cookies.
  • Use HTTPS to prevent token interception.
  • Validate JWTs properly on the server.
  • Blacklist compromised tokens when logging out.

🎯 Final Thoughts

Both sessions and tokens have their pros and cons. While session-based authentication is useful for traditional web applications, token-based authentication is better suited for modern SPAs and APIs. Refresh Tokens provide a way to keep users logged in without exposing security risks.

If you're building an authentication system, understanding these differences will help you choose the right approach based on your needs.

πŸš€ Have questions or thoughts? Drop a comment below!

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly β€” using the tools and languages you already love!

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay