AJAX - Authentication in AJAX
1) Why Authentication Matters in AJAX
-
AJAX calls often talk to protected APIs (e.g., user profiles, orders, payments).
-
The server needs to know who is making the request and whether they’re allowed.
-
Authentication ensures only valid users can access protected resources.
2) Common Authentication Methods in AJAX
a) Session-Based Authentication
-
How it works:
-
User logs in → server creates a session and stores it (e.g., in memory or DB).
-
Server sends a session ID cookie to the browser.
-
Browser includes the cookie with each AJAX request.
-
Server looks up session → authenticates user.
-
Example (AJAX request with session cookie):
fetch("/api/profile", { credentials: "include" }) // sends cookies
.then(res => res.json())
.then(data => console.log(data));
Pros: Simple, widely supported.
Cons: Vulnerable to CSRF unless combined with CSRF tokens or SameSite cookies.
b) Token-Based Authentication (Stateless)
Instead of cookies/sessions, the server issues a token (often JWT = JSON Web Token).
How it works:
-
User logs in → server sends back a token.
-
Client stores it (localStorage, sessionStorage, memory).
-
Client includes token in Authorization header with each AJAX call.
-
Server validates token (signature, expiry).
Example (AJAX with Bearer token):
fetch("/api/profile", {
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
})
.then(res => res.json())
.then(data => console.log(data));
Pros: Works well with APIs, stateless, scales easily.
Cons: If stored in localStorage
, vulnerable to XSS attacks.
c) API Keys
-
Simple authentication method: a static key is sent in request headers or query params.
-
Used for machine-to-machine or public APIs.
Example:
fetch("/api/weather?city=London", {
headers: { "x-api-key": "12345" }
})
.then(res => res.json())
.then(data => console.log(data));
Pros: Easy for simple APIs.
Cons: Not secure for user-based apps (key can be stolen).
d) OAuth 2.0 / OpenID Connect
-
Used when authenticating with third-party services (Google, Facebook, GitHub).
-
The client gets an access token from the OAuth provider.
-
Token is then sent in AJAX requests to access resources.
Example:
fetch("https://api.google.com/userinfo", {
headers: { "Authorization": "Bearer " + accessToken }
});
✅ Pros: Standard for modern apps.
❌ Cons: More complex to implement.
3) Handling Tokens/Sessions Safely
a) For Sessions (Cookies)
-
Use
HttpOnly
andSecure
flags on cookies. -
Use
SameSite=Strict
orLax
to prevent CSRF. -
Combine with CSRF tokens if necessary.
b) For Tokens
-
Prefer Authorization header instead of storing in cookies.
-
Store tokens in memory or
sessionStorage
(notlocalStorage
if possible). -
Refresh tokens when expired (refresh flow).
c) General
-
Always use HTTPS (avoid sending credentials in plain text).
-
Do not expose tokens in URLs (they get logged in history).
4) Example End-to-End Flow with Token Authentication
-
User logs in with credentials.
-
Server responds with:
{ "token": "eyJhbGciOi..." }
-
Client saves token in memory.
-
Client makes AJAX calls with:
Authorization: Bearer eyJhbGciOi...
-
Server validates token → returns protected data.
5) Choosing the Right Method
-
Web app with sessions → Session cookies + CSRF protection.
-
Single Page Application (SPA) → JWT or OAuth tokens.
-
Public API → API keys or OAuth.
Summary:
Authentication in AJAX ensures secure access to APIs:
-
Sessions (cookies) = classic, need CSRF protection.
-
Tokens (JWT, OAuth) = modern, stateless, but must be stored securely.
-
API Keys = good for services, not user auth.