InfoSec Notes
HubCybersecurity vs Information SecurityHistory of Information SecurityImportance of Information SecuritySecurity Principles and the CIA TriadWhat is Information Security?Accountability in Information SecurityAuthentication in Information SecurityAuthorization in Information SecurityAvailability in Information SecurityConfidentiality in Information SecurityIntegrity in Information SecurityNon-Repudiation in Information SecurityAES - Advanced Encryption StandardAsymmetric Key CryptographyDES - Data Encryption StandardDigital SignaturesEncryption vs DecryptionCryptographic Hash FunctionsIntroduction to CryptographyPublic Key Infrastructure (PKI)RSA AlgorithmSymmetric Key CryptographyIntroduction to Access ControlAttribute-Based Access Control (ABAC)Discretionary Access Control (DAC)Mandatory Access Control (MAC)Role-Based Access Control (RBAC) — Information SecurityZero Trust Security ArchitectureFirewalls in Network SecurityIntrusion Detection Systems (IDS)Intrusion Prevention Systems (IPS)Network Monitoring and AnalysisNetwork Security BasicsSecure Network DesignVirtual Private Networks (VPN)Wireless Network SecurityAPI SecurityIntroduction to Application SecuritySecurity Code ReviewDependency and Supply Chain SecurityDynamic Application Security Testing (DAST)Secure Software Development LifecycleStatic Application Security Testing (SAST)Web Authentication MechanismsCross-Site Scripting (XSS)Cross-Site Request Forgery (CSRF)File Upload SecurityHTTPS and SSL/TLSSecure Coding Practices — Information SecuritySession Management SecuritySQL Injection Attacks and PreventionIntroduction to Web SecurityOS Access Control ModelsEndpoint SecurityFile System Permissions and SecurityLinux SecurityIntroduction to OS SecurityUser Account ManagementWindows SecurityCloud Security FundamentalsCloud Security Best PracticesContainer Security — Information SecurityData Security in the CloudCloud Identity and Access ManagementKubernetes SecurityShared Responsibility Model — Information SecurityIntroduction to Digital ForensicsDisk ForensicsDigital Evidence CollectionDigital Forensic ToolsIncident Investigation ProceduresMemory ForensicsNetwork ForensicsContainment StrategiesDetection and Analysis PhaseEradication and RecoveryIntroduction to Incident ResponseIncident Response LifecycleIncident Response PlaybooksPost-Incident Review and Lessons LearnedBusiness Continuity PlanningDisaster Recovery PlanningRisk Assessment MethodologyIntroduction to Risk ManagementSecurity ControlsThreat ModelingVulnerability AssessmentCompliance ManagementGDPR Data Protection OverviewISO 27001 Information Security ManagementNIST Cybersecurity FrameworkSecurity Audits and AssessmentsSecurity GovernanceSecurity Policies and StandardsCloud Security Interview QuestionsCryptography Interview QuestionsInformation Security CheatsheetInformation Security Interview QuestionsNetwork Security Interview QuestionsGlossary of Information Security TermsImportant Security Concepts ReferenceRecommended Books and Learning ResourcesSecurity Tools OverviewIncident Response LabLog Analysis ProjectNetwork Monitoring ProjectPassword Manager ProjectSecure Login System ProjectVulnerability Scanner ProjectInsider ThreatsMalware Types and AnalysisPhishing Attacks and PreventionRansomware AttacksSecurity Threats OverviewSocial Engineering AttacksSpyware and Surveillance SoftwareTrojan Horse MalwareComputer VirusesNetwork Worms
Comprehensive guide to web authentication including sessions, JWT, OAuth 2.0, and passwordless authentication methods.
Overview
Web authentication verifies the identity of users accessing web applications. Modern systems have evolved from simple username/password forms to sophisticated multi-factor, token-based, and passwordless approaches.
Session-Based Authentication
Example
Session Authentication Flow:
==============================
Client Server
| |
| 1. POST /login |
| {username, password} |
|------------------------------>|
| | 2. Validate credentials
| | 3. Create session in store
| 4. Set-Cookie: session_id=abc |
|<------------------------------|
| |
| 5. GET /dashboard |
| Cookie: session_id=abc |
|------------------------------>|
| | 6. Look up session
| | 7. Return user data
| 8. 200 OK (dashboard data) |
|<------------------------------|
JSON Web Tokens (JWT)
Example
import jwt
import datetime
import os
SECRET_KEY = os.environ.get('JWT_SECRET', 'your-secret-key')
def create_jwt_token(user_id: int, email: str, roles: list) -> str:
"""Create a signed JWT token."""
payload = {
"sub": user_id,
"email": email,
"roles": roles,
"iat": datetime.datetime.utcnow(),
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1),
"iss": "myapp.com"
}
return jwt.encode(payload, SECRET_KEY, algorithm="HS256")
def verify_jwt_token(token: str) -> dict:
"""Verify and decode JWT token."""
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"],
issuer="myapp.com")
return {"valid": True, "payload": payload}
except jwt.ExpiredSignatureError:
return {"valid": False, "error": "Token expired"}
except jwt.InvalidTokenError as e:
return {"valid": False, "error": str(e)}
# Usage
token = create_jwt_token(123, "user@example.com", ["admin"])
print(f"JWT: {token[:50]}...")
result = verify_jwt_token(token)
print(f"Valid: {result['valid']}")
JWT Structure
| JWT | xxxxx.yyyyy.zzzzz |
| "alg" | "HS256", |
| "typ" | "JWT" |
| "sub" | "1234567890", |
| "name" | "Alice", |
| "iat" | 1516239022, |
| "exp" | 1516242622 |
OAuth 2.0 Authorization Code Flow
Example
OAuth 2.0 with PKCE (recommended for all clients):
=====================================================
Client Auth Server Resource Server
| | |
| 1. Generate code_verifier + code_challenge |
| | |
| 2. Redirect to /authorize |
| ?response_type=code |
| &client_id=xxx |
| &redirect_uri=callback |
| &code_challenge=sha256(verifier) |
| &code_challenge_method=S256 |
|---------------------->| |
| | |
| 3. User authenticates & consents |
| | |
| 4. Redirect to callback?code=AUTH_CODE |
|<----------------------| |
| | |
| 5. POST /token |
| {code, code_verifier, client_id} |
|---------------------->| |
| | |
| 6. {access_token, refresh_token, id_token} |
|<----------------------| |
| | |
| 7. GET /api/resource |
| Authorization: Bearer {access_token} |
|---------------------------------------------->|
| | |
| 8. Protected resource data |
|<----------------------------------------------|
Session vs JWT Comparison
| Feature | Session-Based | JWT |
|---|---|---|
| Storage | Server-side session store | Client-side token |
| Scalability | Requires shared session store | Stateless, scales easily |
| Revocation | Easy (delete session) | Difficult (wait for expiry) |
| Size | Small cookie (session ID) | Larger (contains claims) |
| Cross-domain | Difficult (cookie scope) | Easy (send in header) |
| Security | Session fixation risk | Token theft risk |
Interview Questions
- What are the security risks of JWT and how do you mitigate them?
- Risks: token theft (store securely, short expiry), no revocation (use blocklist or short-lived tokens + refresh), algorithm confusion (validate
algheader), oversized payload (don't store sensitive data in JWT). Mitigations: HttpOnly cookies for storage, short expiration, refresh token rotation.
- Explain the difference between authentication and session management.
- Authentication verifies identity (login). Session management maintains the authenticated state across subsequent requests. After authentication succeeds, a session token is issued; managing that token's lifecycle (creation, validation, expiry, invalidation) is session management.
- Why is PKCE required for OAuth 2.0 public clients?
- Public clients (SPAs, mobile apps) cannot securely store a client_secret. Without PKCE, an attacker who intercepts the authorization code can exchange it for tokens. PKCE adds a code_verifier that only the legitimate client knows, preventing code interception attacks.
- How would you implement token revocation for JWTs?
- Options: short expiry (5-15 min) with refresh tokens (revoke refresh token), token blocklist in Redis (check on each request), token versioning per user (increment version on logout), or event-driven invalidation. Each trades statefulness for revocation capability.
- What is the difference between OAuth 2.0 and OpenID Connect?
- OAuth 2.0 is an authorization framework (grants access to resources). OpenID Connect (OIDC) adds an identity layer on top: it provides an ID token (JWT) with user identity claims, a UserInfo endpoint, and standardized scopes (openid, profile, email) for authentication.
Continue the lesson path
Study next in this module
01Web SecurityCross-Site Scripting (XSS)Complete guide to XSS vulnerabilities including reflected, stored, and DOM-based XSS attacks with prevention techniques, CSP headers, and practical exploitation examples.02Web SecurityCross-Site Request Forgery (CSRF)Understanding CSRF attacks, how they exploit authenticated sessions, prevention with tokens and SameSite cookies, and implementing anti-CSRF protection.03Web SecurityFile Upload SecuritySecuring file upload features against malicious uploads including shell injection, path traversal, MIME type attacks, and implementing proper server-side validation.04Web SecurityHTTPS and SSL/TLSDeep dive into HTTPS, SSL/TLS protocol handshake, certificate verification, cipher suites, and secure transport layer communication.