Backend · Concept
Authentication and Sessions: How Applications Remember Users
Understand how applications verify identity, carry login state across requests, enforce permissions, and end access without confusing cookies, sessions, tokens, or JWTs.
On this page
The short answer
Authentication verifies a claimed identity. A session or token lets later requests carry evidence of that authenticated state. Authorization then decides whether the identified requester may perform a particular action.
In a common server-side session design, the server stores login state and gives the browser an unpredictable session identifier in a cookie. The browser sends that cookie on requests within its scope. The server uses the identifier to load the session, identify the user, and apply authorization rules.
That is one design, not the definition of authentication. Applications can use other credentials and token models, and every design must make deliberate decisions about storage, expiration, renewal, revocation, and logout.
Identity, authentication, and authorization
Three related questions belong to different stages:
- Identification: Who does the requester claim to be?
- Authentication: What evidence verifies that claim?
- Authorization: Is that verified identity allowed to perform this operation on this resource?
A username can identify an account without proving who submitted it. A password, passkey, one-time code, or external identity-provider result can participate in authentication. A permission check remains necessary afterward.
OWASP defines authentication as verifying that an entity is what it claims to be.Authentication establishes identity; it does not grant every permission.5 RFC 9110 defines 401 Unauthorized around missing or invalid authentication credentials and 403 Forbidden around a server refusing a request it understood.Applications sometimes apply these codes differently, so use the API contract and server evidence too.1
Mental model
Claim an identity → prove it → carry authenticated state → check permission for each protected action
The login screen handles only the first transition. Remembering the user and authorizing later requests are separate responsibilities.
Why applications need login state
One HTTP request does not automatically inherit application identity from an earlier request. A browser can reuse a network connection, but connection reuse is not a user session. Requests may arrive over different connections, at different application instances, or after an earlier process has restarted.
The application therefore needs evidence that connects later requests to an authenticated context. That evidence might be a session identifier in a cookie, a bearer access token in an authorization field, a client certificate, or another credential.
The server must still validate the evidence on every protected request. A page looking logged in because of cached frontend state does not prove that the next API request is authenticated.
The server-side session model
A server-side session usually separates two pieces:
- The browser holds an opaque, unpredictable session identifier.
- The server or a server-side session store holds the state associated with that identifier.
The stored state can include a user identifier, issuance and expiration information, and security context. The identifier should not expose a password or sensitive profile data. If an attacker steals a valid identifier, the application may treat the attacker as the session owner, which is why session identifiers require credential-level protection.
OWASP describes the session identifier as the binding between authenticated state, HTTP traffic, and access controls, while the associated meaning remains server-side.The session store can be memory, a database, a cache, or another deliberately designed repository.6
Server-side does not mean one machine's process memory. With multiple application instances, the session may live in a shared store, use routing affinity, or be reconstructed through another mechanism. Each choice changes availability and revocation behavior.
How cookies participate
A cookie is a browser storage and request mechanism. A server sends Set-Cookie; the browser stores an accepted cookie and later adds it to applicable requests in the Cookie field. RFC 6265 defines this state-management mechanism and shows session identifiers as one use.The browser applies cookie scope and policy before sending it.2
A session is the application's state model across interactions. A cookie can carry the session identifier, but the cookie is not the server-side session. Cookies can also store preferences unrelated to authentication, and a non-browser client can carry a session identifier through another mechanism.
This illustrative response shows attributes, not a production recipe:
Set-Cookie: session=opaque-value; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=1800The identifier is intentionally opaque. A real application should use its framework's maintained session facilities and current security guidance rather than inventing identifier generation or cookie policy from this example.
Important cookie attributes
Securerestricts the cookie to secure transport conditions defined by user-agent behavior. It does not encrypt the cookie value at rest or make the application safe.HttpOnlyprevents ordinary browser JavaScript from reading the cookie through APIs such asdocument.cookie. The browser can still attach it to applicable requests.SameSitecontrols whether the browser includes the cookie in various cross-site contexts.Strict,Lax, andNonehave different behavior;SameSite=NonerequiresSecurein current browsers.Domainbroadens or limits which matching hosts can receive the cookie. Omitting it creates a host-only cookie.Pathlimits the request paths on which the browser sends the cookie. It is routing scope, not a strong security boundary against other code on the same origin.Expiresgives an absolute expiry time.Max-Agegives a lifetime in seconds and takes precedence when both it andExpiresare present.
MDN documents the current browser-facing behavior of these attributes.Cookie defaults and compatibility details can evolve, so production policy should follow current browser documentation.3
HttpOnly reduces one route for stealing a session cookie through JavaScript, but an XSS payload running in the page may still issue requests that the browser sends with the cookie. SameSite reduces some cross-site request risks; it does not replace appropriate CSRF defenses for the application's design.
A complete session-login flow
- SubmitCredentials travel to the login endpoint over HTTPS
- VerifyServer checks the submitted authentication evidence
- CreateServer creates login state with expiration and context
- Set cookieResponse carries an opaque session identifier
- Send againBrowser includes the cookie on applicable requests
- LoadServer resolves valid session state and identity
- AuthorizeApplication checks permission for the requested action
The flow is qualified. Some systems rotate the identifier during login, split session state across stores, or use a managed identity service. Not every application uses a server-side session.
Token-based authentication
A token is data presented as evidence for access. In an HTTP API, a client may send an access token in an Authorization field. The receiving service validates it under the token system's rules and uses its scope or associated state when deciding access.
Tokens can be opaque identifiers that require a server lookup or self-contained structures carrying claims. “Token-based” does not mean stateless, browser-safe, or automatically scalable. Issuance, storage, audience, expiration, rotation, revocation, and transport still need design.
Browser storage is part of the threat model. JavaScript-readable storage exposes values to scripts running in the origin. Cookies add automatic request behavior that affects CSRF analysis. There is no secure choice independent of application architecture and attacker model; OWASP currently recommends avoiding authentication credentials in localStorage and sessionStorage and favors protected cookies or a backend-for-frontend pattern for relevant browser designs.Apply current, architecture-specific guidance rather than a slogan about one storage API.6
What a JWT is
JWT stands for JSON Web Token. RFC 7519 defines it as a compact claims representation encoded using a JSON Web Signature or JSON Web Encryption structure.A JWT can be signed or MAC-protected, encrypted, nested, or even unsecured under the format; the surrounding profile determines what is acceptable.10
A common signed JWT has three base64url-encoded sections separated by dots: a protected header, claims payload, and signature. Base64url encoding is not encryption. Anyone holding such a token can commonly decode its header and payload.
Validation requires more than decoding and more than “the signature matches.” The recipient must use an allowed algorithm and trusted key, then validate relevant context such as issuer, audience, expiration, and any application-specific claims. RFC 7519 states that required claims and their processing depend on the application; it specifically requires rejecting an audience mismatch when an audience claim is present.A structurally valid token can still be unacceptable for this service or request.10
JWT is a format, not an authentication system. It does not choose secure storage, issue trustworthy identities, rotate keys, revoke access, or enforce permissions by itself.
A signed JWT is encrypted
A signature or MAC protects integrity and authenticity under the relevant key. It does not hide the payload. Confidential claims require an appropriate encryption design or should be omitted.
Sessions versus tokens
This comparison is not “stateful versus stateless” in every case:
- A server session commonly uses an opaque identifier and server-side lookup.
- An opaque access token also commonly requires server-side lookup.
- A self-contained token can reduce per-request lookup, but revocation, key management, refresh, and account state still introduce server-side concerns.
- A session identifier may be carried in a cookie; a token may also be carried in a cookie.
Choose from concrete needs: client type, trust boundary, revocation speed, number of services, browser threats, operational capability, and standards being implemented. Many ordinary web applications work well with established server-side sessions and do not need JWTs.
Expiration, renewal, revocation, and logout
- Expiration limits how long credentials or session state are accepted.
- Renewal extends or replaces valid state under defined conditions.
- Rotation replaces an identifier or token, reducing reuse of an older value and helping detect replay in some designs.
- Revocation makes state invalid before its scheduled expiration.
- Logout should end the relevant application state, not merely hide the interface.
For a server-side session, logout commonly invalidates the session in the store and expires the browser cookie using matching scope. RFC 6265 notes that removing a cookie requires matching the original Path and Domain values.Deleting only the browser cookie without invalidating sensitive server-side state can leave stolen identifiers usable.2
Self-contained tokens complicate immediate revocation because a recipient may otherwise accept a valid signature until expiration. Short lifetimes, revocation records, token introspection, version checks, and rotating refresh tokens are architectural options with different costs. “Delete the JWT” affects only the copy being deleted.
Password handling at a high level
Passwords must not be stored as plaintext. Password hashing deliberately transforms a password through a one-way, expensive verification function; reversible encryption serves a different purpose.
A unique salt prevents identical passwords from sharing the same stored result and defeats precomputed tables across accounts. A password-hashing algorithm is deliberately costly so offline guesses are slower. OWASP's current guidance prefers Argon2id for new systems and provides current parameters and alternatives for constrained or legacy environments.Parameters and approved choices can change, so use maintained libraries and current guidance rather than copying constants from an article.7
At login, the application applies the stored algorithm and parameters to the submitted password, then compares the result safely. Rate limiting, multifactor authentication, breached-password screening, monitoring, and reauthentication for sensitive actions address risks that hashing alone cannot.
CSRF and XSS relationships
Cross-site request forgery (CSRF) causes a browser to send an unwanted request to a site where the user already has ambient credentials, commonly cookies. Defenses can include SameSite policy, anti-CSRF tokens, origin verification, and interaction requirements, depending on the request and architecture. OWASP recommends layered CSRF defenses and warns that XSS can defeat many of them.SameSite is useful but not a universal replacement for application-specific protection.8
Cross-site scripting (XSS) allows attacker-controlled script to execute in the application's origin. HttpOnly can stop that script from reading a cookie directly, but the script may still act through the page, read non-HttpOnly data, or make authenticated requests. Preventing XSS requires contextual output encoding, safe DOM usage, sanitization where HTML is allowed, and supporting browser controls.Session-cookie attributes reduce impact; they do not repair unsafe rendering.9
OAuth and OpenID Connect: brief distinctions
OAuth 2.0 is an authorization framework in which a client obtains limited access to protected resources rather than using the resource owner's password directly.Its access token represents delegated access with defined scope, lifetime, and other attributes.11
OpenID Connect adds an identity layer on top of OAuth 2.0. It defines how a client can verify an end user's authentication and receive identity claims, including through an ID Token.A “Login with…” flow normally uses OpenID Connect or another authentication profile when login identity is the goal.12
An OAuth access token is not a universal application session replacement, and an ID Token is not an access token for arbitrary APIs. Correct flows require their own deeper treatment.
Common misconceptions
Cookies and sessions are the same thing
A cookie is a browser storage and request mechanism. A session is application state across interactions. A cookie can carry an identifier for a server-side session.
Authentication means the user may do anything
Authentication establishes identity. Authorization must still evaluate the requested action and resource.
JWT means stateless and secure
JWT defines a token format. Secure use still requires trusted issuance, correct validation, safe storage, expiration, key management, permissions, and a revocation strategy where needed.
HttpOnly solves XSS
It limits direct script access to a cookie. Malicious script can still harm users through the page, so the XSS vulnerability must be prevented and contained.
Debugging scenario
Debugging scenario
The login request succeeds, and the server records a newly created session. The next protected API request returns 401. Browser inspection shows that the session cookie was not included with that request.
What already worked? DNS, connection and TLS, the login endpoint, credential verification, and server-side session creation. The failure occurs between returning the cookie, storing it under browser policy, and attaching it to the later request.
What should you inspect? Check whether the browser accepted Set-Cookie, then examine Domain, Path, Secure, SameSite, Expires, and Max-Age. Compare the request's scheme, host, path, site context, and time. For cross-origin Fetch requests, inspect the request's credentials mode and the server's corresponding cross-origin policy; Fetch credential settings affect whether credentials are sent and whether Set-Cookie is respected.Browser developer tools can show both rejected-cookie reasons and the outgoing request fields.4
No single attribute explains every missing cookie. Record the actual request context before changing several policies at once.
Knowledge check
Reflect, then reveal each answer.
How do identification, authentication, and authorization differ?
Identification states who the requester claims to be. Authentication verifies that claim. Authorization decides whether the verified identity may perform a specific action on a resource.
In a server-side session, what does the browser commonly store?
An opaque session identifier, often in a cookie. The application state associated with it remains in a server-side session store.
What does HttpOnly protect, and what does it not solve?
It prevents ordinary browser JavaScript from reading the cookie. It does not eliminate XSS or stop malicious script from acting through the page with automatically attached credentials.
Why is decoding a JWT not validation?
Decoding only reveals encoded fields. Validation must verify acceptable protection and keys plus relevant claims such as issuer, audience, expiration, and application-specific context.
Login succeeds but the next request omits the session cookie. Which boundary should you inspect?
Inspect browser cookie acceptance and request attachment: scope, security attributes, site and origin context, expiration, Fetch credentials mode, and corresponding server policy.
What to learn next
How this connects
- Deployment and cloud servers
See where session stores, secret configuration, application processes, and identity dependencies run outside a developer machine.
- Reverse proxies and production debugging
Trace which component rejected a credential and correlate browser, proxy, and application evidence.
- Advanced application security
Continue into passkeys, multifactor authentication, OAuth profiles, CSRF defenses, XSS prevention, and threat modeling.
- Authorization design
Model roles, attributes, ownership, policy evaluation, and denial behavior independently of login mechanics.
Key takeaway
References & further reading
References & further reading12 sourcesPrimary standards and official documentation used for this lesson.
- RFC 9110: HTTP Semantics (opens in a new tab)
Internet Engineering Task Force (IETF)
HTTP authentication framework and 401 and 403 response semantics
- RFC 6265: HTTP State Management Mechanism (opens in a new tab)
Internet Engineering Task Force (IETF)
Cookie storage, scope, request transmission, expiration, Secure, and HttpOnly
- Set-Cookie header (opens in a new tab)
MDN Web Docs
Current browser-facing descriptions of cookie attributes including SameSite
- Request: credentials property (opens in a new tab)
MDN Web Docs
Browser Fetch credential behavior for requests and Set-Cookie responses
- Authentication Cheat Sheet (opens in a new tab)
OWASP Foundation
Authentication, secure transport, account defenses, and reauthentication
- Session Management Cheat Sheet (opens in a new tab)
OWASP Foundation
Session identifiers, renewal, expiration, cookies, and browser storage guidance
- Password Storage Cheat Sheet (opens in a new tab)
OWASP Foundation
Current password hashing and salting recommendations
- Cross-Site Request Forgery Prevention Cheat Sheet (opens in a new tab)
OWASP Foundation
CSRF threat model and layered defenses
- Cross Site Scripting Prevention Cheat Sheet (opens in a new tab)
OWASP Foundation
XSS prevention through contextual output handling and browser controls
- RFC 7519: JSON Web Token (JWT) (opens in a new tab)
Internet Engineering Task Force (IETF)
JWT structure, claims, signing, encryption, audience, and expiration semantics
- RFC 6749: The OAuth 2.0 Authorization Framework (opens in a new tab)
Internet Engineering Task Force (IETF)
Delegated authorization roles and access-token model
- OpenID Connect Core 1.0 incorporating errata set 2 (opens in a new tab)
OpenID Foundation
Identity layer built on OAuth 2.0 and ID Token semantics