Skip to content

Session Hijacking — Cookie Theft, Token Attacks, and Prevention

What Is Session Hijacking and Why Does It Matter?

Section titled “What Is Session Hijacking and Why Does It Matter?”

Session hijacking is an attack in which an adversary takes over an active user session by stealing or forging session tokens. The OWASP Session Management Cheat Sheet classifies session hijacking as a critical web security risk, and CWE-384 (Session Fixation) is listed in the CWE/SANS Top 25 Most Dangerous Software Weaknesses.

Session hijacking targets the small pieces of data (cookies, JWTs, session IDs) that web applications use to remember who you are after you log in. Once an attacker has your session token, they become you. They can access your email, your bank account, your admin panel — all without needing your password.

Understanding session hijacking is essential for multiple reasons:

  • Web application security depends on secure session management. Every web app you will protect, test, or build uses sessions, and flawed session handling is a consistently exploited weakness.
  • SOC analysts investigate session theft incidents when users report account takeovers, and must understand how attackers bypass authentication by stealing tokens rather than cracking passwords.
  • Certification exams including CompTIA Security+ SY0-701 and CEH v13 cover session hijacking techniques, cookie security attributes, and prevention mechanisms in detail.
  • Penetration testers routinely test session management as part of web application assessments, checking for missing cookie flags, session fixation, and token predictability.

This page covers how web sessions work, the major session hijacking techniques, and the layered defences that prevent them — explained for beginners with no prior web development experience.

The moment session hijacking clicked for me was during a TryHackMe lab. I used a simple cross-site scripting vulnerability to steal a session cookie, pasted it into my browser, and suddenly I was logged in as the admin — no password required. It felt like finding a master key card on the floor and realising it opens every door in the building. That exercise taught me that authentication is only as strong as the session management that follows it.

Ethical and legal warning: Only test session hijacking techniques on systems you own or have explicit written authorisation to test. Stealing session tokens from real users is a criminal offence under the Computer Fraud and Abuse Act (US), Computer Misuse Act (UK), and Criminal Code Act 1995 (Australia). Practise in your home lab or on authorised platforms.

What Do Real-World Session Hijacking Attacks Look Like?

Section titled “What Do Real-World Session Hijacking Attacks Look Like?”

MITRE ATT&CK documents session hijacking under multiple techniques including T1550.004 — Web Session Cookie and T1185 — Browser Session Hijacking, reflecting its prevalence in real-world intrusion campaigns. Session hijacking is used in targeted attacks, opportunistic theft, and automated exploitation.

ScenarioAttack methodImpact
XSS cookie theftAttacker injects JavaScript into a vulnerable page that sends the victim’s session cookie to an attacker-controlled serverFull account takeover without credentials
Public Wi-Fi sidejackingAttacker on the same network intercepts unencrypted session cookies using a packet snifferAccess to victim’s social media, email, or banking session
Session fixationAttacker sets a known session ID in the victim’s browser before they log in, then uses the same ID after authenticationAttacker gains authenticated access using a pre-set token
Man-in-the-middle (MITM)Attacker intercepts HTTPS-downgraded traffic between client and server, captures session tokens in transitComplete session takeover and potential data modification
Malware token extractionInfo-stealer malware exports session cookies from the victim’s browser storagePersistent access to all authenticated sessions on the device
JWT manipulationAttacker forges or modifies a JSON Web Token due to weak signing or algorithm confusionPrivilege escalation or impersonation of other users

The common thread is that session tokens are bearer credentials — anyone who possesses the token is treated as the authenticated user.

RFC 6265 defines the HTTP State Management Mechanism that governs how cookies — the primary session token transport — are created, stored, and transmitted by browsers. Understanding this mechanism is essential to grasping how session hijacking exploits the web.

To understand session hijacking, you first need to understand what a session is and why it exists. Think of a web session like a wristband at a music festival. You show your ticket (username and password) at the gate once, and you receive a wristband (session token). For the rest of the day, you just show the wristband to access different areas — you do not need to show your ticket again. Session hijacking is someone copying your wristband.

HTTP is a stateless protocol — each request is independent, with no memory of previous requests. Without sessions, you would need to send your username and password with every single page load, API call, and button click. Sessions solve this by creating a temporary identity token after successful authentication.

Token typeWhere it livesHow it works
Session cookieBrowser cookie storageServer generates a random session ID, stores session data server-side, sends the ID to the browser as a cookie. Most common approach.
JWT (JSON Web Token)Cookie or Authorization headerSelf-contained token with encoded user data, signed by the server. The server does not need to store session state.
URL session IDURL query parameterSession ID appended to the URL (e.g., ?sid=abc123). Insecure and largely deprecated — leaks via browser history and referer headers.
Hidden form fieldHTML form dataSession token embedded in hidden form fields. Limited to form-based interactions.
  1. Authentication — User submits credentials. Server validates them against the database.
  2. Token issuance — Server generates a unique, random session token and sends it to the client (typically as a Set-Cookie header).
  3. Subsequent requests — The browser automatically includes the session cookie with every request to the same domain.
  4. Validation — Server checks the session token against its session store for each request to verify the user’s identity.
  5. Termination — Session ends when the user logs out, the token expires, or the server invalidates it.

Step-by-Step: Session Hijacking Attack Methods

Section titled “Step-by-Step: Session Hijacking Attack Methods”
Section titled “1. Cross-Site Scripting (XSS) Cookie Theft”

XSS is the most common method for stealing session cookies. If a web application has an XSS vulnerability, the attacker injects JavaScript that reads the victim’s cookie and sends it to the attacker.

The attack flow: attacker finds an XSS vulnerability (e.g., a comment field that does not sanitise input), injects a script that reads document.cookie and sends it to an external server, victim visits the page and their browser executes the script, the victim’s session cookie is sent to the attacker’s server, and the attacker uses the stolen cookie to impersonate the victim.

The defence: the HttpOnly cookie flag prevents JavaScript from reading the cookie, making XSS-based cookie theft impossible even if an XSS vulnerability exists.

On unsecured networks (public Wi-Fi, unencrypted HTTP), an attacker captures session cookies by sniffing network traffic. The tool Firesheep demonstrated this attack in 2010 by making it trivially easy to hijack Facebook and Twitter sessions on shared Wi-Fi networks.

The defence: HTTPS encrypts all traffic including cookies, making network-level interception useless. HSTS (HTTP Strict Transport Security) ensures the browser never makes unencrypted requests to the domain.

In session fixation, the attacker does not steal a session — they set one. The attacker obtains a valid session ID from the server, forces that session ID into the victim’s browser (via a crafted URL or XSS), and then waits for the victim to log in. After authentication, the server associates the pre-set session ID with the now-authenticated user, and the attacker — who already knows the session ID — gains access.

The defence: regenerate the session ID after successful authentication. The old (fixed) session ID becomes worthless because the server issues a completely new one upon login.

An attacker positioned between the client and server (via ARP spoofing, DNS poisoning, or a rogue Wi-Fi access point) can intercept session tokens in transit. Tools like Bettercap and mitmproxy can intercept and modify traffic in real time.

The defence: HTTPS with certificate pinning, HSTS preloading, and monitoring for certificate anomalies.

While not strictly session hijacking, CSRF exploits the fact that the browser automatically sends session cookies with every request. The attacker tricks the victim’s browser into making a request to a target site (e.g., a bank transfer) while the victim is authenticated. The browser includes the session cookie automatically.

The defence: CSRF tokens (unique per-request tokens), SameSite cookie attribute, and verifying the Origin/Referer headers.

Session Hijacking via XSS Cookie Theft

The most common session hijacking method — exploiting XSS to steal session tokens

Reconnaissance
Find the vulnerability
Discover XSS flaw
Test input fields
Confirm cookie is readable
Injection
Plant the payload
Craft cookie-stealing script
Inject via comment or form
Payload stored on page
Victim Interaction
Trigger execution
Victim visits page
Browser executes script
Cookie sent to attacker
Session Takeover
Impersonate the victim
Attacker receives cookie
Replaces own session cookie
Authenticated as victim
Impact
Exploit access
Access sensitive data
Modify account settings
Escalate privileges
Idle

How Does Session Security Fit Into a Security Architecture?

Section titled “How Does Session Security Fit Into a Security Architecture?”

The OWASP Testing Guide recommends testing session management as a distinct category within every web application security assessment, covering token generation, transport, storage, and lifecycle. Secure session management requires multiple overlapping defences. No single control is sufficient — each layer addresses a different attack vector.

Session Security Defence Layers

From transport encryption to continuous monitoring — each layer prevents a different attack

HTTPS Everywhere + HSTS
Encrypts all traffic, prevents sidejacking and MITM
Secure Cookie Flags
HttpOnly, Secure, SameSite — controls how cookies are sent and accessed
Token Management
Random generation, rotation after login, short expiry, server-side validation
Input Validation
Prevents XSS that enables cookie theft — sanitise all user input
CSRF Protection
Anti-CSRF tokens and SameSite cookies prevent cross-origin request abuse
Session Monitoring
Detect anomalies — IP changes, concurrent sessions, impossible travel
Idle

What Does Session Security Look Like in Practice?

Section titled “What Does Session Security Look Like in Practice?”

The MDN Web Docs reference for Set-Cookie defines the HttpOnly, Secure, and SameSite attributes that form the browser-enforced layer of session security.

Terminal window
# Secure cookie header — what a properly configured session cookie looks like:
Set-Cookie: session_id=a8f3e9b1c2d4; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=3600
# Breaking down each attribute:
# HttpOnly — JavaScript CANNOT read this cookie (blocks XSS cookie theft)
# document.cookie will NOT include this cookie
# Secure — Cookie is ONLY sent over HTTPS connections
# Prevents interception on unencrypted HTTP
# SameSite=Strict — Cookie is NOT sent with cross-origin requests
# Prevents CSRF attacks entirely
# SameSite=Lax — Cookie sent with top-level navigations but not embedded requests
# Less restrictive but still blocks most CSRF
# Path=/ — Cookie applies to all paths on the domain
# Max-Age=3600 — Cookie expires after 1 hour (3600 seconds)
# Short session lifetimes limit the window for hijacking

Testing Session Security with Browser DevTools

Section titled “Testing Session Security with Browser DevTools”
// In browser DevTools Console (F12 > Console tab):
// Check if cookies are accessible to JavaScript (HttpOnly test)
document.cookie
// If session cookie appears here, HttpOnly is NOT set — vulnerability!
// Check cookie attributes in the Application tab:
// DevTools > Application > Cookies > [domain]
// Look for: HttpOnly checkbox, Secure checkbox, SameSite value
// Test session fixation — does the session ID change after login?
// 1. Note the session cookie value BEFORE logging in
// 2. Log in
// 3. Check the session cookie value AFTER logging in
// If it is the SAME value, session fixation is possible — vulnerability!
Terminal window
# Burp Suite Community Edition — intercept and analyse session tokens
# 1. Configure browser proxy to 127.0.0.1:8080
# 2. Navigate to target application login page
# 3. In Burp Suite Proxy > HTTP History, find the login response
# Look for Set-Cookie headers:
# - Is the session ID sufficiently random? (at least 128 bits of entropy)
# - Are HttpOnly and Secure flags set?
# - Does the session ID change after authentication?
# 4. Use Burp Sequencer to test token randomness:
# Proxy > right-click response > Send to Sequencer
# Sequencer analyses the statistical randomness of session tokens
# Tokens with low entropy can be predicted by attackers
Section titled “Python Script to Demonstrate Cookie Theft Impact”
# Requires: requests>=2.31.0
# Educational demonstration — how a stolen cookie grants access
# ONLY use on systems you own or have authorisation to test
import requests
# Attacker has stolen this session cookie from the victim
stolen_cookie = {"session_id": "a8f3e9b1c2d4"}
# Attacker makes a request using the stolen cookie
response = requests.get(
"https://vulnerable-app.local/dashboard",
cookies=stolen_cookie
)
# If session management is weak, the attacker sees the victim's dashboard
print(response.status_code) # 200 = access granted
print(response.text[:200]) # Shows victim's private data
# This is why HttpOnly + Secure + short expiry + session binding matter
# With proper controls, this stolen cookie would be rejected

What Are the Limitations of Session Security?

Section titled “What Are the Limitations of Session Security?”

The OWASP Session Management Cheat Sheet warns that no single session security control is sufficient — each defence addresses a different attack vector, and gaps in any layer create exploitable weaknesses.

FactorLimitationHow to handle it
HTTPS adoptionOlder internal applications may still use HTTP, exposing session tokens on the networkEnforce HTTPS everywhere, use HSTS preloading, redirect all HTTP to HTTPS
HttpOnly gapsSome legitimate JavaScript frameworks need cookie access for functionalityUse separate cookies: HttpOnly for session authentication, accessible cookies only for non-sensitive preferences
Session timeout UXShort session timeouts improve security but frustrate users who get logged out frequentlyBalance security and usability — 30-60 minutes for standard apps, shorter for sensitive operations with re-authentication
Token rotation complexityRotating tokens after every request can cause race conditions in applications with concurrent AJAX requestsRotate on significant events (login, privilege change, IP change) rather than every request
JWT revocationJWTs are self-contained — once issued, they are valid until expiry even if the user’s account is compromisedUse short-lived JWTs (15 minutes) with refresh tokens, maintain a server-side revocation list for critical invalidation
Client-side storagelocalStorage and sessionStorage are accessible to JavaScript, making them vulnerable to XSSStore sensitive tokens in HttpOnly cookies, never in localStorage

A common beginner mistake is assuming that HTTPS alone makes sessions secure. HTTPS prevents network-level interception but does nothing against XSS-based cookie theft, session fixation, or CSRF. Every layer in the defence stack addresses a different attack vector.

What Interview Questions Should You Expect About Session Hijacking?

Section titled “What Interview Questions Should You Expect About Session Hijacking?”

Session management is tested in CompTIA Security+ SY0-701 (Domain 2 — Threats, Vulnerabilities, and Mitigations) and in the OWASP Web Security Testing Guide methodology used by most penetration testing firms.

Session management questions test your understanding of web security fundamentals — knowledge expected in SOC, application security, and penetration testing roles.

Q1: What is session hijacking?

Strong answer: “Session hijacking is an attack where an adversary takes over an active user session by obtaining the session token — typically a session cookie or JWT. Since web applications use tokens to maintain authenticated state, anyone who possesses a valid token is treated as the authenticated user. The attacker does not need the user’s password — they only need the session token.”

Q2: What are the HttpOnly and Secure cookie flags, and why do they matter?

Strong answer: “HttpOnly prevents JavaScript from accessing the cookie via document.cookie. This is critical because it blocks the most common session hijacking method — XSS-based cookie theft. Even if an attacker finds an XSS vulnerability, they cannot read an HttpOnly cookie. The Secure flag ensures the cookie is only sent over HTTPS connections, preventing interception on unencrypted networks. Together, they address the two most common session theft vectors: XSS and network sniffing.”

Q3: A user reports their account was accessed by someone else, but their password was not changed. What could have happened?

Strong answer: “The most likely explanation is session hijacking — the attacker obtained the user’s session token rather than their credentials. I would investigate how the token was stolen: check for XSS vulnerabilities that could enable cookie theft, review login logs for concurrent sessions from different IP addresses or geolocations, check if the user connected from an untrusted network where sidejacking could occur, and look for info-stealer malware on their device. I would invalidate all active sessions, force re-authentication, and review the application’s cookie security flags.”

Q4: What is the SameSite cookie attribute?

Strong answer: “SameSite controls whether the browser sends the cookie with cross-origin requests. SameSite=Strict means the cookie is never sent with requests originating from a different site — this prevents CSRF attacks entirely. SameSite=Lax allows the cookie on top-level navigations like clicking a link but blocks it on embedded requests like images, forms, and AJAX calls from other sites. SameSite=None allows the cookie on all cross-origin requests but requires the Secure flag. Most modern browsers default to Lax when no SameSite value is set.”

Q5: How does session fixation differ from session hijacking?

Strong answer: “In traditional session hijacking, the attacker steals an existing session token after the victim authenticates. In session fixation, the attacker sets a known session token before the victim authenticates, then waits for the victim to log in using that token. The attacker already knows the session ID because they chose it. The fix is to regenerate the session ID after successful authentication, so the pre-set token becomes invalid.”

How Is Session Hijacking Used in Real Security Operations?

Section titled “How Is Session Hijacking Used in Real Security Operations?”

The MITRE ATT&CK framework classifies web session cookie theft as a credential access technique (T1550.004), commonly observed in advanced persistent threat (APT) campaigns targeting enterprise environments.

As a new SOC analyst, session-related incidents require investigation across multiple data sources:

  • Account takeover investigation. When a user reports unauthorised account activity, check authentication logs for concurrent sessions from different locations. Look for impossible travel — sessions from Australia and Eastern Europe within minutes of each other indicate session theft rather than credential sharing.
  • XSS incident response. If an XSS vulnerability is reported or exploited, assess whether session cookies were exposed. Check if HttpOnly is set on session cookies. If not, treat all active sessions as potentially compromised and force global re-authentication.
  • Suspicious session patterns. SIEM rules can detect anomalies like session tokens used from multiple IP addresses, sessions that persist beyond the configured timeout, or sudden changes in user-agent strings mid-session — all indicators of session hijacking.
  • Web application firewall (WAF) tuning. Review WAF logs for blocked XSS attempts and CSRF violations. These alerts indicate attackers probing for session hijacking entry points.

The ASD Essential Eight includes restricting administrative privileges and multi-factor authentication — both of which limit the impact of session hijacking. If an attacker hijacks a standard user session, MFA on privileged actions (like admin panel access or sensitive data export) creates an additional barrier.

The ACSC’s Information Security Manual (ISM) includes controls for web application security that encompass session management. Australian government agencies are expected to implement secure cookie attributes, session timeout policies, and protection against common web attacks including XSS and CSRF.

Under the Notifiable Data Breaches scheme, if session hijacking leads to unauthorised access to personal information, the organisation must assess whether the breach meets the notification threshold. For organisations in the financial sector regulated by APRA, CPS 234 (Information Security) requires controls to protect the confidentiality of information assets — which includes session tokens that grant access to customer data.

Session hijacking exploits the fundamental mechanism that keeps users logged in — session tokens — making it one of the most impactful web application attacks.

  • Session tokens are bearer credentials. Anyone who possesses a valid session token is treated as the authenticated user. Protecting these tokens is as important as protecting passwords.
  • XSS is the primary enabler. Cross-site scripting enables cookie theft, which is the most common path to session hijacking. The HttpOnly flag blocks this vector entirely.
  • HTTPS prevents network-level theft. Without encryption, session cookies are visible to anyone on the same network. HTTPS with HSTS preloading eliminates sidejacking.
  • Cookie flags are your first line of defence. HttpOnly, Secure, and SameSite — three attributes that collectively block XSS theft, network sniffing, and CSRF.
  • Regenerate tokens after authentication. This single control prevents session fixation attacks by ensuring pre-authentication session IDs cannot be used post-login.
  • Short session lifetimes limit exposure. Even if a token is stolen, a 30-minute expiry limits how long the attacker can use it.
  • Defence in depth is essential. No single control prevents all session hijacking methods. HTTPS, cookie flags, input validation, CSRF tokens, and session monitoring work together.

Individual results vary. Career timelines, salary outcomes (source: BLS and CyberSeek, as of 2025), and job availability depend on your location, experience, market conditions, and effort. The information on this page is educational, not a guarantee of employment outcomes.

  • Web Application Hacking for the broader context of web security including XSS and injection attacks
  • SQL Injection for another critical web application vulnerability that can expose session data
  • Sniffing for the network-level interception techniques used in session sidejacking

Frequently Asked Questions

What is session hijacking in simple terms?

Session hijacking is when an attacker steals the token (usually a cookie) that a website uses to remember that you are logged in. Once they have your token, they can access your account without knowing your password. It is like someone copying your building access card — they can enter everywhere you can.

What is the difference between session hijacking and session fixation?

In session hijacking, the attacker steals an existing session token after you log in. In session fixation, the attacker sets a known session token in your browser before you log in, then uses that same token after you authenticate. Hijacking steals your key; fixation gives you a key the attacker already has a copy of.

How does the HttpOnly cookie flag prevent session hijacking?

The HttpOnly flag tells the browser that JavaScript cannot access this cookie through document.cookie. This blocks XSS-based cookie theft — the most common session hijacking method. Even if an attacker injects malicious JavaScript into the page, the script cannot read the session cookie to steal it.

Can HTTPS prevent all session hijacking?

No. HTTPS prevents network-level session theft (sidejacking) by encrypting all traffic including cookies. However, it does not protect against XSS-based cookie theft, session fixation, or CSRF. HTTPS is necessary but not sufficient — you also need HttpOnly cookies, session ID regeneration, CSRF tokens, and input validation.

What is the SameSite cookie attribute?

SameSite controls whether the browser sends a cookie with requests originating from a different website. Strict means the cookie is never sent cross-site. Lax allows it for top-level navigations but blocks embedded requests. None allows all cross-site requests but requires the Secure flag. SameSite=Strict or Lax prevents most CSRF attacks.

What is a JWT and how can it be hijacked?

A JSON Web Token (JWT) is a self-contained session token that encodes user information and is signed by the server. JWTs can be hijacked through XSS (if stored in localStorage), network interception (if transmitted without HTTPS), or algorithm confusion attacks (if the server accepts unsigned or weakly signed tokens). Unlike server-side sessions, JWTs cannot be easily revoked once issued.

How do I test if a web application is vulnerable to session hijacking?

Check the session cookie attributes in browser DevTools (Application tab > Cookies). Verify HttpOnly, Secure, and SameSite are set. Test session fixation by noting the session ID before login and checking if it changes after login. Use Burp Suite Sequencer to test token randomness. Check if the application uses HTTPS everywhere with HSTS. Always test only on systems you have authorisation to assess.

What is Firesheep and why was it important?

Firesheep was a Firefox extension released in 2010 that made session sidejacking trivially easy on public Wi-Fi networks. It could automatically capture unencrypted session cookies from other users on the same network and let the attacker log into their accounts with one click. Firesheep was a major catalyst for the industry's adoption of HTTPS everywhere.

Is session hijacking covered on CompTIA Security+ SY0-701?

Yes. CompTIA Security+ SY0-701 covers session hijacking under Domain 2 (Threats, Vulnerabilities, and Mitigations) and Domain 3 (Security Architecture). Topics include session management attacks, cookie security attributes, XSS, CSRF, and secure communication protocols. Understanding both the attacks and the defences is required for the exam.

What should I do if I suspect my session has been hijacked?

Immediately log out of the application (this invalidates your session token on the server). Change your password from a trusted device. Enable multi-factor authentication if available. Review recent account activity for unauthorised actions. Check your device for malware using an antivirus scan. If the compromised account is a work account, report it to your IT security team immediately.


Technical content verified in March 2026 against OWASP Session Management Cheat Sheet (2024), CompTIA Security+ SY0-701 exam objectives, CEH v13 syllabus, and RFC 6265 (HTTP State Management Mechanism).