Understanding Authentication, Authorization, Cookies, Sessions, and JWT: A Complete Guide

This article explains the fundamentals of authentication and authorization, the role of credentials, how cookies and sessions manage state, the differences between tokens, JWT and traditional session mechanisms, and practical considerations and best practices for secure implementation in web applications.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Understanding Authentication, Authorization, Cookies, Sessions, and JWT: A Complete Guide

What is Authentication

In simple terms, authentication verifies a user's identity, proving "you are yourself" (e.g., fingerprint clock‑in works when the fingerprint matches the stored one).

What is Authorization

Authorization is the user granting a third‑party application permission to access certain resources.

When installing a mobile app, it may request access to photos, location, etc.

When using a WeChat mini‑program, it may ask for nickname, avatar, region, gender, and other personal information.

Common ways to implement authorization include cookies, sessions, tokens, and OAuth.

What are Credentials

Credentials are the medium (certificate) that marks a visitor's identity for authentication and authorization.

Historically, the State of Qin issued "Zhao Shen Tie" (a smooth bamboo board with the holder's portrait and origin) as a credential.

In everyday life, a resident ID card serves as a legal credential to prove identity for services such as mobile phone registration, banking, loans, and transportation.

On the web, sites like Juejin have guest and logged‑in modes; after a successful login the server issues a token that identifies the user for subsequent requests.

What is a Cookie

HTTP is stateless, so servers need a mechanism (cookie or session) to track whether consecutive requests come from the same browser.

A cookie is a small piece of data stored on the client; it is sent with each request to the same server.

Cookies are domain‑bound and cannot be shared across different domains (sub‑domains can share via the domain attribute).

Important cookie attributes are illustrated below:

What is a Session

Session is another mechanism for recording server‑client session state.

Session is built on cookies: the session data lives on the server, while the session ID is stored in a client‑side cookie.

Session authentication flow:

The user makes the first request; the server creates a corresponding session.

The server returns the unique SessionID to the browser.

The browser stores the SessionID in a cookie, which also records the domain.

On subsequent requests the browser sends the cookie; the server retrieves the session via SessionID and validates the login state.

Thus SessionID bridges the cookie and the session, and many systems use this principle to verify login status.

Differences Between Cookie and Session

Security: Session data resides on the server, making it more secure than client‑side cookies.

Data type: Cookies store only strings; sessions can store any data type.

Expiration: Cookies can be long‑lived; sessions typically expire when the browser closes or after a timeout.

Size: A single cookie is limited to ~4 KB, while sessions can store much larger data but may consume server memory under heavy load.

What is a Token (令牌)

Access Token

Credential required to access a resource API.

Simple token composition: uid (user identifier), time (timestamp), sign (hash‑derived signature).

Features:

Stateless server, good scalability.

Supports mobile devices.

Secure.

Supports cross‑program calls.

Token authentication flow:

Client sends username and password to log in.

Server validates credentials.

On success, the server issues a token and returns it to the client.

Client stores the token (e.g., in a cookie or localStorage).

Client includes the token in the Authorization header of each request.

Server validates the token and, if valid, returns the requested data.

Each request must carry the token, typically placed in the HTTP Authorization header.

Token‑based authentication is stateless; the server does not store token data, reducing database queries.

Tokens are managed entirely by the application, allowing them to bypass same‑origin restrictions.

Refresh Token

A refresh token is used solely to obtain a new access token without requiring the user to re‑enter credentials.

Access tokens have short lifetimes; when they expire, the refresh token can be used to get a new one. Refresh tokens are stored server‑side and validated only when a new access token is requested, avoiding impact on API response time.

Differences Between Token and Session

Session records server‑client state, making the server stateful; token (including JWT) is a credential for API access, keeping the server stateless.

Tokens generally provide better security because each request includes a signature that prevents replay attacks, whereas sessions rely on transport‑layer security.

Sessions store user info on the server; JWTs embed the information in the token itself, eliminating the need for server‑side lookups.

What is JWT

JSON Web Token (JWT) is a popular cross‑domain authentication solution.

It is a mechanism for authentication and authorization.

JWT follows the RFC 7519 standard to transmit claims between an identity provider and a service provider.

It can be signed with HMAC or RSA keys, making the payload trustworthy.

JWT Principles

JWT Authentication Flow

User logs in with username/password; on success the server returns a JWT.

Client stores the JWT (commonly in localStorage or a cookie).

When accessing a protected route, the client sends the token in the Authorization header using the Bearer scheme.

Authorization: Bearer <token>

The server validates the JWT; if valid, the request proceeds.

Because JWTs are self‑contained, they reduce the need for database lookups.

JWTs do not rely on cookies, so they avoid CORS issues and enable truly stateless authentication.

How to Use JWT

Clients may store the JWT in a cookie or localStorage.

Method 1

Place the JWT in the Authorization header (Bearer) for protected requests; this avoids cross‑domain limitations of cookies.

GET /calendar/v1/events Host: api.example.com Authorization: Bearer <token>

This keeps the server stateless and reduces database queries.

Method 2

For cross‑origin calls, include the JWT in the POST request body.

Method 3

Transmit the JWT via URL query parameters, e.g., http://www.example.com/user?token=xxx.

Differences Between Token and JWT

Both are access tokens that can carry user information and enable stateless servers.

Traditional tokens require the server to look up user data in a database; JWTs embed the data and can be verified solely with a secret key.

Common Front‑end and Back‑end Authentication Methods

Session‑Cookie

Token verification (including JWT, SSO)

OAuth 2.0 (open authorization)

Common Encryption Algorithms

Hash algorithms create a small digital fingerprint of data, ensuring data integrity. They are fast to compute, hard to reverse, sensitive to input changes, and have a low collision probability.

Note: Hashes alone do not guarantee protection against malicious tampering; combining them with RSA signatures provides stronger guarantees.

Common Issues

Considerations When Using Cookies

Client‑side storage makes cookies vulnerable to tampering; validate them.

Never store sensitive data (e.g., passwords, balances).

Use HttpOnly to improve security.

Keep cookie size small (max ~4 KB).

Set appropriate domain and path.

Cookies cannot be shared across domains.

Browsers limit the number of cookies per site (≈20) and overall (≈300).

Mobile browsers have limited cookie support; tokens are often preferred.

Considerations When Using Sessions

Sessions consume server memory; large concurrent user bases require cleanup of expired sessions.

In clustered deployments, session sharing becomes a challenge.

Cross‑domain applications need to handle cookie sharing.

If cookies are disabled, session IDs can be passed via URL rewriting.

Mobile environments often favor tokens over sessions.

Considerations When Using Tokens

Tokens can be stored in fast in‑memory stores like Redis to avoid database latency.

Tokens are managed by the application, bypassing same‑origin restrictions.

Tokens can mitigate CSRF attacks because cookies are not required.

Mobile clients typically use tokens.

Considerations When Using JWT

JWTs are not encrypted by default, though they can be encrypted.

Never place secret data in an unencrypted JWT.

JWTs can be used for both authentication and information exchange, reducing database queries.

Because the server does not store JWT state, revoking a specific token is difficult; set short lifetimes.

If a JWT is leaked, all its permissions are exposed; use HTTPS and short expiration.

Use JWTs for one‑time commands with very short validity.

Considerations When Using Encryption Algorithms

Never store passwords in plain text.

Always hash passwords; never use reversible encoding like Base64.

Use strong password‑hashing algorithms; avoid weak hashes like MD5 or SHA‑1.

Never transmit or display passwords in plain text; for password‑reset, generate a one‑time password.

Session Sharing Solutions in Distributed Architecture

1. Session Replication

When a session changes on any server, the session is serialized and broadcast to all other nodes, ensuring synchronization.

Pros: fault‑tolerant, real‑time response across servers.

Cons: adds network overhead; large session volumes may cause congestion.

2. Sticky Session / IP Binding Strategy

Using Nginx's ip_hash, all requests from a given IP are routed to the same server, effectively binding the user to that server.

Pros: simple, no session handling required.

Cons: lacks fault tolerance; if the server fails, the user loses session state.

Suitable when server failures are rare and impact is minimal.

3. Session Sharing (Common)

Store sessions in a distributed cache such as Memcached or Redis (clustered).

Enables session sharing.

Allows horizontal scaling by adding Redis nodes.

Sessions survive server restarts.

Supports cross‑platform sharing (web and app).

4. Session Persistence

Persist sessions to a database to guarantee durability.

Pros: sessions survive server crashes.

Cons: high database load under heavy traffic and additional maintenance overhead.

Sessions are not automatically removed when the browser closes; they persist until the server deletes them after a timeout or explicit logout.

When the browser is closed, the session cookie may disappear, but the server‑side session remains until it expires.

Link: Original Article

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

TokenAuthorizationCookie
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.