Web Security & Performance Optimization

Chapter 4
Identity, Authentication and Access Control

Bachelors Program in Full Stack Development
Web Security & Performance Optimization   •   Bachelor

Identity, Authentication and Access Control

Introduction

Identity systems answer three related but distinct questions:

  1. Who is the subject? — identification.
  2. Can the subject prove that claim? — authentication.
  3. What may the authenticated subject do? — authorization.

A secure web application must also preserve these decisions across requests. This is the purpose of session management. Identity failures are especially serious because they can expose personal data, permit financial fraud, or allow attackers to act with another person’s privileges. The objective is therefore not merely to add a login form, but to design a trustworthy identity lifecycle: registration, credential use, authentication, session establishment, authorization, recovery, monitoring, and revocation.

This chapter examines secure sessions, password storage, multifactor and passwordless authentication, authorization models, OAuth 2.0, OpenID Connect, JSON Web Tokens (JWTs), secrets management, and defenses against identity and session attacks.

Learning Objectives

By the end of this chapter, students should be able to:

  • distinguish identification, authentication, authorization, and accounting;
  • design secure cookie-based sessions and explain their security attributes;
  • select appropriate password-hashing and password-recovery practices;
  • compare multifactor, passkey, and passwordless authentication;
  • apply RBAC, ABAC, DAC, and capability-oriented authorization models;
  • explain the roles of OAuth 2.0 and OpenID Connect;
  • validate, rotate, revoke, and safely use JWTs;
  • manage application secrets and identity-provider credentials;
  • identify and mitigate identity, credential, and session attacks;
  • evaluate an identity architecture from security, usability, privacy, and governance perspectives.

1. Identity as a Security System

An identity is a representation of a person, service, device, or organization within a system. An identity record may contain identifiers, attributes, credentials, roles, consent records, and audit history. An identifier such as an email address is not proof of identity; it is only a label.

Authentication factors are commonly classified as:

FactorMeaningExamples
KnowledgeSomething the subject knowsPassword, PIN
PossessionSomething the subject hasHardware security key, authenticator device
InherenceSomething the subject isFingerprint, face recognition
Location or behaviorContextual evidenceNetwork location, typing pattern

Multifactor authentication (MFA) requires evidence from at least two distinct factor categories. Two passwords are two knowledge elements, not MFA. Biometrics should generally unlock a local device or credential rather than be transmitted to a server as a reusable secret.

Authorization decisions should be based on a stable subject identifier, not solely on mutable display data such as a username or email address. A mature system also maintains accounting or auditability: records of important authentication and authorization events, with appropriate privacy controls.

2. The Identity Lifecycle

Identity security is a lifecycle rather than a single endpoint:

  • Enrollment: create an account and establish an initial authenticator.
  • Proofing: assess whether the claimed person or organization is genuine. High-risk services may require stronger evidence than ordinary applications.
  • Authentication: verify one or more authenticators.
  • Session establishment: create a bounded representation of the authenticated state.
  • Authorization: evaluate whether the subject may perform a requested action on a resource.
  • Maintenance: update attributes, factors, roles, and recovery methods.
  • Suspension and revocation: disable access after compromise, departure, or policy violation.
  • Recovery: restore access without creating an easier attack path than normal login.

Security controls should be proportional to risk. A public discussion forum and a payroll system should not necessarily use identical proofing, authentication, session duration, or approval requirements.

3. Password Storage and Credential Security

Passwords must never be stored in plaintext or with reversible encryption. A database administrator, backup recipient, or attacker who obtains the database should not be able to directly recover every password.

A password verifier stores a salted, deliberately expensive password hash. For password p, salt s, and cost parameters c, the stored verifier can be represented conceptually as:

v = KDF(p, s, c)

Here, v is the derived verifier; KDF is a password-specific key-derivation function; s is a unique random salt; and c specifies work and memory settings. The equation is a model, not a recommendation to implement a cryptographic function manually. Appropriate choices include Argon2id, scrypt, or bcrypt, configured according to current platform guidance and periodically reviewed against available hardware.

A salt is not a secret. Its purpose is to ensure that equal passwords do not produce equal stored values and to prevent useful precomputed tables. A server-side pepper is an additional secret kept outside the database, often in a secrets manager or hardware security module. A pepper can add defense in depth, but it does not replace a salt or a strong password KDF.

During login, the application retrieves the user’s salt and parameters, computes a candidate verifier, and compares it using a constant-time comparison where appropriate. It should not reveal whether an account exists. Rate limits, breached-password screening, MFA, and anomaly detection complement hashing; hashing alone does not prevent online guessing.

Password policies should favor long, memorable passwords or passphrases and should reject known-compromised passwords. Arbitrary complexity rules can encourage predictable transformations. Password changes should be required after evidence of compromise or according to justified organizational policy, not merely at arbitrary frequent intervals.

Secure Recovery

Recovery is authentication. It should use short-lived, single-use, high-entropy reset tokens, store only a protected representation of those tokens where feasible, invalidate them after use, and avoid exposing account existence. Email recovery is dependent on the security of the email account. Support-based recovery requires carefully controlled identity proofing and fraud-resistant procedures.

4. Secure Sessions

HTTP is stateless, so applications need a mechanism to associate successive requests with an authenticated subject. The preferred pattern for many browser applications is an opaque, random session identifier in a cookie. The server stores the meaningful session state; the browser stores only the identifier.

A secure session design should:

  • generate identifiers with a cryptographically secure random generator;
  • use sufficient entropy and never derive identifiers from usernames, timestamps, or predictable values;
  • set cookies with Secure, so they are sent only over HTTPS;
  • set HttpOnly, reducing exposure to JavaScript-based cookie theft;
  • set an appropriate SameSite value to reduce cross-site request forgery (CSRF);
  • use a narrow Domain and Path scope;
  • avoid placing session identifiers in URLs, logs, referrers, or analytics data;
  • regenerate the identifier after login, privilege elevation, and other sensitive transitions;
  • expire idle and absolute sessions according to risk;
  • revoke sessions after logout, password reset, suspected compromise, or account disablement.

HttpOnly does not stop cross-site request forgery, and SameSite is not a complete substitute for CSRF defenses in every deployment. State-changing requests should use an anti-CSRF token or an equivalent robust design, and servers should validate the request context where appropriate.

A common attack is session fixation, in which an attacker causes a victim to use a session identifier known to the attacker and then waits for the victim to authenticate. Regenerating the identifier after authentication prevents the pre-authentication identifier from becoming the authenticated session.

Session cookies should not contain unnecessary personal data. If a stateless token is used, its disclosure can be equivalent to a bearer credential. Logout should invalidate server-side state when possible; deleting a browser cookie alone may not invalidate a copied credential.

Secure browser session establishment flow BrowserCredentials + cookie ApplicationVerify and authorize Session storeSubject and expiry After successful authenticationRegenerate identifier → store server-side state → issue Secure,HttpOnly, appropriately SameSite cookie
Secure browser session establishment flow
Figure: Secure browser session establishment flow

Figure: A server-side session pattern in which the browser holds an opaque cookie and the application holds session meaning.

5. Multifactor and Passwordless Authentication

MFA reduces the impact of stolen passwords, but implementations differ substantially.

  • Time-based one-time passwords (TOTP): an authenticator and server share a secret and independently generate short-lived codes. Phishing sites can relay a code in real time, so TOTP is stronger than passwords alone but weaker than phishing-resistant methods.
  • Push approval: a device receives a login request. Number matching, rate limits, and context display reduce approval fatigue.
  • Hardware security keys and passkeys: WebAuthn/FIDO2 uses public-key cryptography. The private key remains protected by the authenticator, while the server stores a public key. Origin binding makes credential phishing substantially harder.
  • SMS codes: useful in limited recovery or transitional scenarios, but vulnerable to SIM swapping, number reassignment, interception, and social engineering. They should not be treated as equivalent to phishing-resistant authentication for high-risk systems.

In passwordless authentication, the user may unlock a local credential with a PIN or biometric. The biometric generally stays on the device; the server verifies a cryptographic assertion. Systems should provide secure enrollment, device replacement, recovery, and revocation procedures.

Authentication should be step-up capable. A low-risk profile view may need an ordinary session, while changing a payout account should require recent MFA and possibly an explicit transaction confirmation.

6. Authorization Models

Authentication establishes a subject; authorization determines whether an operation is allowed on a resource in a context. A useful decision considers subject, action, resource, environment, and policy.

Discretionary Access Control

In DAC, resource owners can grant access. It is flexible but can become difficult to govern when users widely share permissions.

Role-Based Access Control

RBAC assigns permissions to roles and roles to users. For example, support_agent may read support tickets, while billing_admin may issue refunds. RBAC improves manageability, but excessive role creation can cause role explosion. Separation-of-duties constraints can prevent one person from both creating and approving a payment.

Attribute-Based Access Control

ABAC evaluates attributes such as department, resource classification, device trust, time, and transaction value. A policy might permit a clinician to view records only for assigned patients and only from an approved context. ABAC is expressive, but policies require disciplined ownership, testing, and explainability.

Capability-Oriented Designs

A capability is an unforgeable reference that conveys authority to a particular operation or resource. Carefully scoped, short-lived capabilities can support sharing and delegation, but leakage is dangerous because possession may equal permission.

Regardless of model, enforce authorization on the server for every sensitive request. Do not rely on hidden interface elements, client-side route guards, or user-supplied role fields. Apply least privilege, deny by default, validate object ownership, and test for insecure direct object references—situations in which changing an identifier exposes another user’s object.

7. OAuth 2.0 and OpenID Connect

OAuth 2.0 is an authorization framework for delegated access to resources. It is not, by itself, an identity or login protocol. A resource owner can authorize a client to obtain an access token for a limited scope at a resource server.

The principal roles are:

  • Resource owner: commonly the user;
  • Client: the application requesting access;
  • Authorization server: issues authorization codes and tokens;
  • Resource server: accepts access tokens and serves protected resources.

For browser and mobile applications, the Authorization Code flow with Proof Key for Code Exchange (PKCE) is the normal modern pattern. The client creates a high-entropy verifier, derives a challenge, sends the challenge in the authorization request, and later presents the verifier when exchanging the code. This binds the code exchange to the initiating client and mitigates interception of the authorization code.

Applications should use exact, pre-registered redirect URIs; validate the state value to bind the response to the initiated transaction; use nonce when OpenID Connect is involved; request narrow scopes; and avoid implicit delivery of access tokens through browser URLs. Authorization servers should support secure client authentication appropriate to the client type and should not treat a public client as capable of safely storing a client secret.

OpenID Connect (OIDC) adds an identity layer to OAuth 2.0. It supplies an ID token, normally a JWT, containing claims about authentication and the subject. The client must validate the token’s signature, issuer, audience, time claims, and nonce where applicable. An ID token is intended for the client; it should not casually be sent to an API as though it were an access token. An access token’s meaning is defined by the resource server and its authorization server configuration.

8. JWT Handling

A JWT commonly has a header, payload, and signature. It may carry claims such as issuer (iss), subject (sub), audience (aud), expiration (exp), not-before (nbf), and issued-at (iat). Base64url encoding is not encryption. Anyone who obtains an ordinary signed JWT can usually read its payload.

Safe validation requires an explicit trust configuration:

  1. select permitted algorithms from server configuration, not from untrusted input;
  2. verify the signature using the correct trusted key;
  3. validate the issuer and intended audience;
  4. enforce expiration and not-before with a small, justified clock-skew allowance;
  5. validate token type and required claims;
  6. check scopes, roles, or permissions against the requested operation;
  7. reject malformed, oversized, or otherwise unexpected tokens.

Do not accept an algorithm merely because the token header requests it. Do not use a public token decoder as a validator. Key rotation requires a planned overlap period, key identifiers, secure publication of verification keys, and retirement of old keys after tokens they signed can no longer be valid.

JWTs are useful when distributed verification and bounded, self-contained claims are valuable. They are not automatically superior to server-side sessions. Long-lived JWTs complicate revocation, and putting sensitive information in them increases disclosure risk. Keep access tokens short-lived, minimize claims, protect refresh tokens, rotate them where appropriate, and store browser credentials in a design resistant to script and cross-site attacks.

9. Secrets Management

Secrets include database passwords, signing keys, OAuth client credentials, API keys, encryption keys, and recovery codes. They should not be committed to source control, embedded in client-side bundles, printed in logs, or shared through informal messaging.

A secrets-management program should provide:

  • centralized storage with encryption and strict access control;
  • workload identity and short-lived credentials where feasible;
  • separation between development, test, and production secrets;
  • automated rotation and documented emergency revocation;
  • audit trails for access and changes;
  • secret scanning in repositories and build pipelines;
  • redaction of secrets from logs, traces, error messages, and crash reports;
  • dual control or approval for especially sensitive signing keys.

Environment variables can be preferable to source code for deployment injection, but they are not automatically safe: processes, crash dumps, build systems, and operators may expose them. A secret manager or hardware-backed key service is more appropriate for high-value keys. Rotation cannot compensate for uncontrolled access; least privilege and observability remain essential.

10. Identity and Session Attacks

Important attacks and defenses include:

ThreatTypical mechanismPrincipal defenses
Credential stuffingReuse of breached passwordsMFA, breached-password screening, rate limits, anomaly detection
Brute forceRepeated guessingAdaptive throttling, lockout with care, MFA, monitoring
PhishingDeceptive login or consent pagePasskeys, origin checks, user education, verified flows
Session hijackingTheft of a valid sessionHTTPS, secure cookies, XSS prevention, short lifetimes, revocation
Session fixationVictim authenticates with attacker-known IDRegenerate session after authentication
CSRFCross-site state-changing requestAnti-CSRF tokens, SameSite cookies, origin checks
Token replayReuse of intercepted bearer tokenTLS, short lifetimes, sender-constrained tokens where justified
Account enumerationDifferent responses reveal account existenceUniform messages and timing, controlled recovery responses
Privilege escalationMissing or inconsistent authorizationServer-side deny-by-default checks and object-level tests
MFA fatigueRepeated prompts cause accidental approvalNumber matching, risk-based limits, user-visible context

Cross-site scripting is an identity threat because injected script may act through a victim’s browser and potentially access non-HttpOnly credentials. Strong output encoding, content security policy where appropriate, secure dependency management, and input handling are therefore part of session security.

Monitoring should record authentication successes and failures, factor enrollment and removal, recovery events, token anomalies, privilege changes, and administrative actions. Logs should support investigation without storing passwords, raw reset tokens, or unnecessary personal data.

11. Applied Case: Illustrative University Research Portal

Background

An illustrative university research portal allows students and staff to access projects, datasets, and grant documents. The first version uses passwords, a long-lived JWT in local storage, and client-side role checks.

Problem

A tester changes a project identifier in an API request and reads another researcher’s project. A malicious browser extension or injected script can also extract the JWT. Password reuse produces several account compromises, while administrators cannot reliably revoke access when a student leaves a project.

Analysis

The system confuses authentication with authorization. The client’s role display is treated as an enforcement mechanism, object ownership is not checked, and the long-lived bearer token creates a large replay window. Local storage is exposed to scripts running in the page. The portal also lacks a coherent lifecycle for project membership and factor revocation.

Approach and Solution

The redesign uses an external OIDC provider with Authorization Code plus PKCE. The portal maintains a server-side session with an opaque, rotated cookie. Passwords are handled by the identity provider using a memory-hard password KDF, and staff and graduate researchers enroll passkeys or another approved MFA method.

The portal maintains project membership in its own authorization service. Every API request checks the authenticated subject, requested project, action, and current membership. A combination of RBAC and resource-level rules is used: a project owner can manage membership, a contributor can read approved datasets, and a reviewer can read but not alter submissions. Access defaults to deny.

Short-lived access tokens are used only when the portal calls an API that requires them. Token claims are validated for issuer, audience, signature, and time. Membership changes invalidate relevant server-side sessions or trigger re-evaluation on every request. Audit records capture membership changes, data exports, factor changes, and administrative actions.

Outcome

Changing an identifier no longer grants access because authorization is evaluated against the project membership. Session revocation becomes practical, token exposure is reduced, and phishing resistance improves through passkeys. The solution also makes policy ownership explicit: identity-provider administrators manage authentication, while the research portal owns project authorization.

Learning Points

The case demonstrates that no single technology solves identity security. OIDC does not replace application authorization; JWTs do not automatically provide revocation; MFA does not correct object-level access-control errors; and a secure browser credential still requires XSS and CSRF defenses.

12. Governance, Privacy, and Contemporary Practice

Identity systems process sensitive personal data. Collect only attributes necessary for a stated purpose, define retention periods, restrict administrative access, and provide appropriate transparency. Biometric data deserves particular care because it cannot be changed like a password. Risk-based authentication should not become opaque discrimination: decisions should be explainable, reviewable, and monitored for unequal impact.

Organizations should assign ownership for identity policy, maintain an inventory of authenticators and integrations, conduct threat modeling, and test authorization with both unit and adversarial tests. Standards and guidance evolve; implementation teams should consult current recommendations from recognized security bodies and the relevant legal regime rather than treating a framework as permanently fixed.

Emerging practice favors phishing-resistant passkeys, continuous risk signals, workload identity for services, and least-privilege authorization. Artificial intelligence may assist anomaly detection or support triage, but automated identity decisions can produce false positives, privacy risks, and difficult-to-explain outcomes. Human review and measurable appeal processes remain important for consequential decisions.

Best-Practice Design Checklist

  • Treat authentication and authorization as separate controls.
  • Prefer phishing-resistant MFA for high-value accounts.
  • Hash passwords with a current password-specific KDF and unique salts.
  • Regenerate sessions after authentication and privilege changes.
  • Use secure, narrowly scoped cookies and server-side revocation where feasible.
  • Enforce object-level authorization on every sensitive server request.
  • Use OAuth 2.0 with Authorization Code and PKCE for suitable delegated access.
  • Use OIDC when an application needs authenticated identity claims.
  • Validate JWTs against explicit issuer, audience, algorithm, key, and time policies.
  • Keep tokens and secrets short-lived or rotatable, and never log them.
  • Design recovery, factor enrollment, and factor removal as high-risk operations.
  • Monitor identity events and test failure paths, not only successful logins.
  • Minimize identity data and document governance responsibilities.

Chapter Summary

Identity security begins by distinguishing identification, authentication, authorization, and accounting. Passwords should be protected with salted, deliberately expensive password KDFs, while recovery and MFA must be treated as authentication controls. Secure browser sessions use unpredictable identifiers, carefully configured cookies, rotation, expiry, revocation, and CSRF defenses. MFA is strongest when phishing-resistant public-key credentials such as passkeys are used.

Authorization models include DAC, RBAC, ABAC, and capability-oriented designs. Regardless of model, applications must enforce least privilege, deny by default, and check resource ownership on the server. OAuth 2.0 delegates authorization; OpenID Connect adds an identity layer. JWTs require strict validation and are not automatically preferable to server-side sessions. Secrets require centralized governance, limited exposure, rotation, and auditing. Effective identity architecture combines technical controls with lifecycle management, privacy protection, monitoring, usability, and accountable governance.

Key Terms

Identification: Claiming or naming an identity.

Authentication: Verifying a claimed identity.

Authorization: Determining whether a subject may perform an action.

Accounting: Recording security-relevant activity for accountability.

Credential: Evidence used to authenticate a subject.

Password KDF: A deliberately expensive function used to derive a password verifier.

Salt: A unique non-secret random value added to password derivation.

Pepper: An additional secret used as defense in depth for password verification.

Session fixation: Attack in which a victim authenticates using an attacker-known session identifier.

CSRF: Forcing a browser to issue an unwanted state-changing request.

RBAC: Authorization based on roles assigned to subjects.

ABAC: Authorization based on attributes and policy conditions.

OAuth 2.0: Framework for delegated access to protected resources.

OpenID Connect: Identity layer built on OAuth 2.0.

JWT: Signed or encrypted token format for claims exchange.

PKCE: Mechanism binding an authorization-code exchange to a client-generated verifier.

Passkey: A discoverable public-key credential designed for convenient, phishing-resistant authentication.

Bearer token: Token whose possession is sufficient to use it.

Secrets manager: Controlled system for storing, delivering, rotating, and auditing secrets.

Least privilege: Granting only the authority necessary for a task.

Review Questions

Short Answer Questions

  1. Distinguish authentication from authorization.
  2. Why is a unique salt used when storing passwords?
  3. What security properties do Secure and HttpOnly provide for cookies?
  4. Why is OAuth 2.0 not by itself an authentication protocol?
  5. What is the purpose of PKCE?

Long Answer Questions

  1. Explain how a secure server-side session should be established, maintained, and revoked.
  2. Compare RBAC and ABAC, including advantages, limitations, and suitable applications.
  3. Describe secure JWT validation and explain why decoding a JWT is not validation.
  4. Compare passwords, TOTP, SMS codes, and passkeys as authentication methods.
  5. Explain how secrets-management practices reduce the impact of credential compromise.

Analytical / Application Questions

  1. A web application checks a user’s role in JavaScript but does not check ownership of records in its API. Analyze the vulnerabilities and propose a redesign.
  2. A company wants to use a long-lived JWT in browser local storage for single sign-on. Evaluate the proposal and recommend a safer architecture.
  3. Design an authentication and authorization lifecycle for a university system in which students join and leave research projects, including enrollment, step-up authentication, revocation, auditing, and recovery.

Multiple Choice Questions with Answers

Question 1

Which statement best distinguishes authentication from authorization?

A. Authentication assigns roles, while authorization stores passwords.

B. Authentication verifies identity, while authorization determines permitted actions.

C. Authentication encrypts traffic, while authorization compresses tokens.

D. Authentication records logs, while authorization generates salts.

Correct Answer: B. Authentication verifies identity, while authorization determines permitted actions.

Question 2

What is the principal purpose of a unique password salt?

A. To make the password recoverable by administrators

B. To replace the need for a password KDF

C. To prevent equal passwords from producing equal stored verifiers

D. To authenticate a user without a password

Correct Answer: C. To prevent equal passwords from producing equal stored verifiers

Question 3

Which cookie attribute prevents JavaScript from directly reading a cookie?

A. Secure

B. HttpOnly

C. SameSite=None

D. Domain

Correct Answer: B. HttpOnly

Question 4

Which action most directly prevents session fixation after login?

A. Displaying the username in the header

B. Increasing the cookie Path

C. Regenerating the session identifier

D. Adding a profile photo

Correct Answer: C. Regenerating the session identifier

Question 5

Which method is generally the most resistant to phishing?

A. SMS one-time code

B. Password-only login

C. TOTP code entered into a website

D. Passkey using a platform authenticator

Correct Answer: D. Passkey using a platform authenticator

Question 6

What is OAuth 2.0 primarily designed to provide?

A. Delegated authorization to protected resources

B. A password-hashing algorithm

C. A browser cookie specification

D. A database encryption format

Correct Answer: A. Delegated authorization to protected resources

Question 7

What does PKCE protect in the Authorization Code flow?

A. The password database from offline cracking

B. The authorization code from being used by an intercepting client

C. The user’s browser history from all tracking

D. The resource server from denial-of-service attacks

Correct Answer: B. The authorization code from being used by an intercepting client

Question 8

Which validation is required when an API accepts a JWT?

A. Trusting the algorithm named by the token without configuration

B. Checking only that the token has three encoded parts

C. Verifying signature, issuer, audience, and relevant time claims

D. Decrypting every JWT with the user’s password

Correct Answer: C. Verifying signature, issuer, audience, and relevant time claims

Question 9

Which authorization practice best prevents insecure direct object references?

A. Hiding object identifiers in the user interface

B. Checking object ownership and permission on the server for each request

C. Using longer URLs for object identifiers

D. Allowing the client to submit its own role claim

Correct Answer: B. Checking object ownership and permission on the server for each request

Question 10

Which item should normally be excluded from application logs?

A. A timestamp for a failed login

B. A reason code for a rejected request

C. A raw password-reset token

D. A pseudonymous subject identifier

Correct Answer: C. A raw password-reset token

Web Security & Performance Optimization
Chapter 4 of 15