Ankit KanojiyaIntermediate

Evergreen guide by Ankit Kanojiya · Intermediate · Backend

Authentication and Authorization: Sessions, JWT, and OAuth2

How sessions, JSON Web Tokens, and OAuth2 differ, and when each belongs in a backend. Covers the common security trade-offs for each approach.

Authentication answers who a caller is; authorization answers what that caller may do. Backends conflate the two at their peril. This article separates the concepts and then compares the three mechanisms teams reach for most often.

Authentication vs Authorization

Authentication verifies identity, usually by checking a password, a token, or a trusted third party. Authorization is the policy layer that decides whether an authenticated principal can perform a specific action on a specific resource. A system can authenticate a user correctly and still make authorization mistakes, which is why access checks must live close to the data, not only at the edge.

Session-Based Authentication

The classic approach stores server-side session state and hands the client an opaque session identifier in a cookie.

  • The server creates a session record on login and returns a cookie.
  • Each request includes the cookie; the server looks up the session.
  • Logout deletes the session record, so revocation is immediate.

Sessions are simple to reason about and easy to revoke. The cost is state: every request needs access to the session store, which is usually Redis or a database. Secure cookie flags are essential.

Set-Cookie: sid=abc123; HttpOnly; Secure; SameSite=Lax; Path=/

HttpOnly blocks JavaScript access, mitigating token theft via cross-site scripting. SameSite reduces cross-site request forgery exposure, though state-changing endpoints should still carry CSRF protection.

JSON Web Tokens

A JWT is a signed, self-contained token. It carries claims the server can verify without a database lookup.

{
  "sub": "user_42",
  "role": "editor",
  "exp": 1735689600
}

The token has three parts: a header, a payload of claims, and a signature. The server validates the signature and expiry, then trusts the claims.

The appeal is statelessness: any server holding the signing key can validate a token, which suits horizontally scaled services. The hard part is revocation. Because the token is self-contained, a logout or a compromised token cannot be invalidated before it expires unless extra machinery is added.

The common pattern is a short-lived access token paired with a longer-lived refresh token:

  • Access tokens expire in minutes, limiting the damage of a leak.
  • Refresh tokens are stored server-side so they can be revoked.
  • A revocation list or token version counter handles emergencies.

Two frequent mistakes deserve attention. First, never accept the alg field blindly; pin the expected algorithm so an attacker cannot switch it to none. Second, do not place secrets in the payload, because it is only base64-encoded, not encrypted.

OAuth2 and Delegated Access

OAuth2 is an authorization framework for delegated access. It lets a user grant one application limited access to resources held by another, without sharing a password. It is what powers "sign in with" buttons and third-party integrations.

The most common flow is Authorization Code with PKCE:

  1. The app redirects the user to the authorization server.
  2. The user authenticates and consents to specific scopes.
  3. The authorization server returns a short-lived code.
  4. The app exchanges the code plus a PKCE verifier for tokens.

PKCE protects public clients, such as mobile and single-page apps, that cannot keep a client secret. Scopes express granularity: a token might allow read:orders but not write:orders.

A crucial distinction: OAuth2 handles authorization, not identity. OpenID Connect is the layer built on top of OAuth2 that adds authentication by issuing an ID token describing the user. Using raw OAuth2 as a login mechanism without OpenID Connect is a well-known source of security bugs.

Choosing an Approach

  • A single web application with a backend it controls is well served by sessions. Revocation is trivial and the model is easy to audit.
  • A fleet of internal services or a public API often benefits from short-lived JWTs for stateless verification, backed by refresh tokens for revocation.
  • Third-party access, partner integrations, and social login call for OAuth2, with OpenID Connect when identity is needed.

These are not mutually exclusive. A browser session can protect the main app while the backend mints JWTs for service-to-service calls.

Authorization Models

Once identity is settled, decide how permissions are expressed.

  • Role-based access control assigns permissions to roles and roles to users. It is simple and covers most needs.
  • Attribute-based access control evaluates rules over attributes of the user, resource, and context, which suits fine-grained policies.

Whatever the model, enforce checks on the server for every request. Hiding a button in the UI is not access control; the backend must assume any request can be forged and verify authorization each time.

Summary

Keep authentication and authorization distinct. Sessions trade statefulness for easy revocation, JWTs trade easy revocation for stateless scale, and OAuth2 solves delegated access rather than login. Match the mechanism to the trust boundary, and never let a client-side check stand in for a server-side one.