Web Application Security and Secure Coding

Chapter 5
Identity, Authentication and Session Security

Post Graduate Diploma in Full Stack Development
Web Application Security and Secure Coding   •   Post Graduate

5. Identity, Authentication and Session Security

Introduction and Context

Web applications increasingly act on behalf of users, organizations, and automated services. They retrieve personal information, authorize payments, modify business records, and expose functions through application programming interfaces (APIs). Before an application can decide whether an action is permitted, it must establish who or what is making the request and maintain that identity reliably throughout an interaction. These responsibilities are addressed through identity, authentication, and session security.

Identity answers the question, “Which account, person, service, or device is this?” Authentication provides evidence for that identity. Authorization then determines what the authenticated entity may do. Session management connects authentication to subsequent HTTP requests, which are otherwise independent and stateless. A weakness in any one of these areas can permit account takeover, privilege escalation, data theft, fraudulent transactions, or unauthorized administrative access.

The subject is broader than implementing a login form. It includes password storage, credential recovery, multifactor authentication (MFA), passwordless methods, session cookies, tokens, federation, OAuth 2.0, OpenID Connect (OIDC), and defenses against automated credential attacks. Secure design also requires governance: organizations must determine which identity provider to trust, how long sessions should remain active, what evidence is sufficient for sensitive operations, and how authentication events are monitored.

Learning Objectives

After studying this chapter, students should be able to:

1. Distinguish identity, authentication, authorization, and accounting.

2. Design secure password storage, login, recovery, and rate-limiting mechanisms.

3. Compare passwords, MFA, passkeys, certificates, and other authenticators.

4. Implement secure session cookies, session renewal, logout, and session revocation.

5. Explain the roles of OAuth 2.0 and OpenID Connect and select suitable flows.

6. Evaluate JSON Web Token (JWT) use, federation arrangements, and token risks.

7. Analyze credential attacks and develop layered defenses.

8. Apply professional, legal, ethical, and governance considerations to authentication systems.

Identity as a Security Boundary

An identity is a representation of a subject within a security domain. The subject may be a human user, an organization, a device, an application, or a background service. An account identifier, such as an email address or internal user ID, is not proof of identity; it is merely a claim or lookup value.

Authentication is the process of verifying a claim using one or more authentication factors. The classic factor categories are:

  • Knowledge: something the subject knows, such as a password or PIN.
  • Possession: something the subject has, such as a hardware security key or authenticator device.
  • Inherence: something the subject is, such as a biometric characteristic.
  • Context: information about location, device posture, or behavior, which is generally supplementary rather than a complete factor.

Authorization is a separate decision. A successful login does not automatically authorize every operation. For example, an authenticated employee may view an invoice but not approve it. Accounting and auditing record relevant security events, including authentication attempts, changes to recovery factors, privilege changes, and administrative actions. This identity-and-access sequence is often summarized as identification, authentication, authorization, and accountability.

A sound design uses unique internal subject identifiers rather than treating mutable attributes such as email addresses as permanent identity keys. It also defines account lifecycle processes: registration, verification, suspension, recovery, role changes, and deprovisioning.

Passwords: Storage, Verification, and Recovery

Passwords remain common because they are inexpensive and familiar, but they are weak when reused, short, predictable, exposed in breaches, or collected through phishing. Applications must therefore protect passwords both during transmission and at rest.

A password must never be stored in plaintext or with reversible encryption merely so that the application can “decrypt” it later. Instead, the server stores a password hash produced by a deliberately slow, memory-intensive password-hashing algorithm. Suitable modern choices include Argon2id, scrypt, or bcrypt, configured according to current operational capacity. A unique random salt is generated for every password. The salt prevents identical passwords from producing identical stored values and makes precomputed rainbow-table attacks substantially less useful. The salt need not be secret and is normally stored with the hash.

A password verifier receives a submitted password, retrieves the account’s salt and cost parameters, computes a comparison hash, and uses a constant-time comparison where appropriate. It should not reveal whether an account exists. Login failures should produce a broadly consistent response such as “Invalid credentials,” avoiding account enumeration through messages or noticeably different timing.

Password policy should emphasize length and resistance to known-compromised passwords rather than arbitrary complexity rules that encourage predictable substitutions. Password managers should be supported, pasted passwords should not be automatically blocked, and passwords should not be changed periodically without evidence of compromise. Password reset links must be random, single-use, short-lived, transmitted only through secure channels, and invalidated after use. A reset should normally revoke existing sessions and may require reauthentication for high-risk actions.

Password recovery is an authentication process, not a customer-service convenience. Security questions based on public information, predictable email links, or support procedures that accept weak personal details can defeat otherwise strong login controls. Recovery channels require their own protection, logging, and risk assessment.

Multifactor and Passwordless Authentication

MFA reduces the impact of stolen passwords because an attacker must obtain an additional factor. Time-based one-time passwords (TOTP) are widely used, but the secret seed must be protected and enrollment must be authenticated. Push notifications can be convenient, though repeated approval prompts may cause “push fatigue.” Number matching and transaction context reduce accidental approvals.

Hardware security keys and passkeys use public-key cryptography. During registration, the authenticator creates a key pair; the server stores the public key while the private key remains protected by the authenticator. During login, the authenticator signs a server challenge. WebAuthn and the FIDO2 ecosystem bind credentials to the legitimate website origin, making them significantly more resistant to ordinary phishing than passwords and manually entered codes.

Biometrics are generally used to unlock a local device or authenticator rather than being sent directly to the application. They provide convenience but introduce privacy, accessibility, and irrevocability concerns: a compromised password can be replaced, whereas a biometric trait cannot readily be changed. Organizations should provide secure alternative methods without making the alternative an easy bypass.

MFA must protect enrollment, replacement, recovery, and factor removal. An attacker who can call support and replace the registered security key has effectively bypassed MFA. High-value operations should use step-up authentication, in which the user supplies a recent or stronger authentication event before changing payment details, exporting sensitive records, or managing administrators.

Session Security in a Stateless Protocol

HTTP does not inherently remember previous requests. A session mechanism associates subsequent requests with an authenticated context. The most common browser approach is a session cookie containing an unpredictable, high-entropy session identifier. The server stores the session state or maintains it in a protected session service.

Session identifiers must be generated using a cryptographically secure random generator. They should not contain usernames, timestamps, sequential values, or sensitive information. On successful authentication, the application must issue a new session identifier. This prevents session fixation, where an attacker causes a victim to use a session ID known to the attacker and then benefits when the victim authenticates.

Important cookie attributes include:

  • Secure: sends the cookie only over HTTPS.
  • HttpOnly: prevents ordinary client-side scripts from reading the cookie, reducing some theft through cross-site scripting.
  • SameSite: limits cross-site cookie transmission and helps reduce cross-site request forgery (CSRF), although it is not a universal CSRF defense.
  • Appropriate Domain and Path: restricts where the cookie is sent.

Applications should use HTTPS throughout the session, apply HSTS where appropriate, and avoid placing session identifiers in URLs, browser history, referrer headers, or logs. Idle timeouts and absolute lifetimes should reflect risk. A banking session and a low-risk news preference session should not have identical policies. Logout should invalidate the server-side session or otherwise make its credential unusable; deleting a browser cookie alone is insufficient when the server still accepts the identifier.

Session management also includes concurrent-session visibility, revocation after password or factor changes, protection of administrative sessions, and controls for stolen devices. Session data should be stored securely, with authorization checked on every sensitive request rather than inferred from a session’s existence.

OAuth 2.0, OpenID Connect, and Federation

OAuth 2.0 is an authorization framework for delegated access. It enables a client application to obtain limited access to a resource server on behalf of a resource owner. OAuth is not, by itself, an authentication protocol. Treating the presence of an OAuth access token as proof of the user’s identity is a common design error.

The principal roles are the resource owner, client, authorization server, and resource server. In the authorization code flow, the client redirects the user to the authorization server, receives a short-lived authorization code, and exchanges it for tokens. Modern browser and mobile applications should use Authorization Code with Proof Key for Code Exchange (PKCE). PKCE binds the authorization request to the later token exchange and reduces the value of an intercepted code. The client must validate the redirect URI, use state to protect request correlation and CSRF, and use nonce when OIDC is involved.

Access tokens should be narrowly scoped, audience-restricted, short-lived where practical, and transmitted only over protected connections. Refresh tokens require stronger protection and rotation or reuse detection where feasible. Clients must not expose confidential client secrets in browser code or mobile applications, because such applications cannot reliably keep secrets secret.

OpenID Connect adds an identity layer to OAuth 2.0. An ID token is intended for the client and contains claims about authentication, such as the issuer, subject, audience, issue time, and nonce. The client must validate the token’s signature, issuer, audience, expiry, and nonce according to the provider’s metadata and cryptographic configuration. An ID token should not be sent to an API as though it were an access token; the API should receive an access token intended for that resource server.

Federation allows one organization or identity provider to accept authentication performed by another trusted provider. SAML remains common in enterprise environments, while OIDC is prevalent in modern web and mobile systems. Federation reduces duplicated credentials but creates trust dependencies. Trust metadata, signing keys, claims mapping, clock handling, account-linking rules, and deprovisioning procedures must be governed explicitly. Automatic account linking based only on an unverified email address can allow account takeover.

Tokens and Their Security Properties

A token is a bearer or proof-based credential. A bearer token grants access to whoever possesses it, so leakage through logs, browser storage, source code, error reports, or URLs can be catastrophic. Token design must address confidentiality, integrity, audience, issuer, expiry, revocation, and replay.

JWTs are signed data structures that can be useful when services need to validate claims without contacting a central session store. They are not automatically encrypted, and their payload is usually readable. A JWT validator must use an allowlisted algorithm, validate the signature with the correct trusted key, check issuer and audience, enforce temporal claims, and reject malformed or excessively large tokens. It must not accept an algorithm choice supplied by an attacker or confuse a token’s header with a trust decision.

JWTs are often overused. For browser sessions, an opaque server-side session identifier can make revocation and data minimization simpler. If JWTs are chosen, teams must plan key rotation, key distribution, revocation or short lifetimes, and behavior when permissions change. Sensitive personal data should not be placed in a token merely because the format permits it.

Defending Against Credential Attacks

Credential stuffing uses username-password pairs obtained from unrelated breaches. Password spraying tries a small number of common passwords against many accounts, while brute force repeatedly guesses passwords against one account. Phishing captures credentials or induces users to approve fraudulent MFA requests. Adversaries may also target reset workflows, help desks, token stores, and compromised endpoints.

Effective defense is layered. Applications should use breached-password screening, MFA or passkeys, rate limits, progressive delays, IP and device reputation, bot detection, anomaly monitoring, and carefully designed account recovery. Rate limits should avoid creating an easy denial-of-service mechanism against individual accounts. A combination of per-account, per-IP, device, and global controls is more resilient than a single threshold.

Monitoring should distinguish normal user errors from coordinated attacks. Useful signals include impossible travel, unusual device changes, high-volume failures, token reuse, suspicious recovery activity, and rapid privilege changes. Automated responses must be proportionate: a temporary challenge may be preferable to permanent account lockout. Security teams should preserve sufficient evidence for investigation while minimizing unnecessary personal data.

Illustrative Case Study: A Federated Student Services Portal

Background

A university introduces a portal through which students register for courses, view grades, manage fees, and access digital library services. The portal delegates authentication to the university identity provider using OIDC. Several independent services consume access tokens issued during the login process.

Situation and Problem

An initial implementation accepts any valid JWT signed by a key found through a token-supplied key reference. It also uses the ID token to call APIs, stores tokens in browser local storage, and does not rotate the session after login. A password reset link remains valid for 48 hours. The university observes suspicious grade-access requests and repeated password-reset attempts.

Analysis

The design has multiple weaknesses. Trusting a key reference from the token can enable key-confusion or attacker-controlled key attacks if key retrieval is not constrained. Failure to validate audience permits a token issued for one service to be presented to another. Using an ID token as an API credential confuses authentication with authorization. Browser-accessible token storage increases the impact of cross-site scripting. A long-lived reset link creates a valuable recovery credential, and failure to renew the session permits session fixation.

Approach and Solution

The university establishes an explicit trust configuration for the issuer and approved signing keys. Each API validates signature, issuer, audience, expiry, and required scopes. The portal uses the Authorization Code flow with PKCE, validates state and nonce, and keeps access tokens in a protected server-side session where possible. The application issues a fresh session identifier after authentication and uses Secure, HttpOnly, and appropriate SameSite cookie settings.

Reset links become single-use and expire quickly; password resets revoke active sessions and notify the account holder. MFA is required for staff and for sensitive student operations, with passkeys offered as an additional phishing-resistant method. Rate limits and breached-password checks are introduced, while security monitoring detects token reuse and abnormal access patterns.

Outcome

The revised architecture separates identity assertions from API authorization, limits the usefulness of stolen credentials, and makes investigation more reliable. It also creates a repeatable process for key rotation, provider changes, factor recovery, and account deprovisioning.

Learning Points

The case illustrates that authentication security is an ecosystem property. Correct cryptography cannot compensate for incorrect audience validation, unsafe storage, weak recovery, or missing lifecycle governance. Federation reduces password duplication but does not eliminate the need for local session and authorization controls.

Professional and Governance Considerations

Authentication decisions affect accessibility, privacy, and equality of treatment. Biometric or behavioral systems require a lawful purpose, data minimization, transparency, retention controls, and alternatives for users who cannot use them. MFA enrollment should account for lost devices, disability, travel, and organizational support without weakening assurance for everyone.

Organizations should define ownership of identity data, retention periods for authentication logs, incident escalation procedures, and responsibilities between the application team and identity provider. Regulatory obligations vary by jurisdiction and sector, but principles such as least privilege, privacy by design, breach response, and demonstrable access control are widely relevant. Authentication logs should support accountability without becoming an unnecessary repository of sensitive information.

Current Directions and Best Practices

The movement toward passkeys reflects a broader shift from shared secrets to phishing-resistant public-key authentication. Continuous and risk-adaptive access models evaluate device health, session age, requested action, and behavioral signals rather than relying only on a login event. Zero-trust architectures similarly require explicit verification and authorization for each access path.

AI-assisted detection can help identify credential stuffing, unusual login patterns, and account takeover indicators. However, models may produce false positives, encode bias, or be manipulated by attackers. They should augment—not replace—well-defined controls, human review, and transparent incident procedures.

A practical security baseline is to use modern password hashing, breached-password checks, MFA or passkeys, secure recovery, session renewal, protected cookies, short-lived and audience-limited tokens, PKCE for public clients, strict issuer and claim validation, layered rate limiting, comprehensive monitoring, and regular testing of enrollment, logout, reset, and deprovisioning paths.

Chapter Summary

Identity identifies a subject, authentication verifies that identity, authorization determines permitted actions, and accounting records relevant events. Secure password handling requires salted, adaptive password hashing and carefully designed recovery. MFA and passkeys reduce dependence on passwords, but enrollment and recovery must receive equivalent protection. Sessions must use unpredictable identifiers, secure cookie attributes, renewal after authentication, appropriate expiry, and reliable server-side invalidation.

OAuth 2.0 delegates authorization, whereas OpenID Connect adds an identity layer. Secure implementations use Authorization Code with PKCE, validate state, nonce, issuer, audience, signatures, and expiry, and keep access and identity tokens conceptually separate. JWTs and federation introduce operational responsibilities involving key management, trust, claims, revocation, and deprovisioning. Credential attacks require layered defenses combining strong authenticators, rate controls, monitoring, recovery protection, and governance.

Key Terms

Identity: A representation of a person, service, device, or organization within a security domain.

Authentication: Verification of a claimed identity.

Authorization: A decision about which actions or resources an authenticated subject may access.

MFA: Authentication using two or more independent factors.

Passkey: A phishing-resistant public-key credential commonly implemented through WebAuthn or FIDO2.

Salt: A unique random value combined with a password before hashing.

Adaptive password hash: A deliberately costly password hash whose computational or memory cost can be increased.

Session fixation: An attack in which a victim is induced to authenticate using a session identifier known to the attacker.

Session cookie: A browser cookie used to associate requests with an application session.

CSRF: An attack that causes a browser to submit an unwanted authenticated request.

OAuth 2.0: A framework for delegated authorization and access-token issuance.

OpenID Connect: An identity protocol built on OAuth 2.0.

PKCE: A mechanism binding an authorization request to its subsequent code exchange.

Access token: A credential presented to a resource server to obtain authorized access.

ID token: An OIDC token intended to communicate authentication information to a client.

JWT: A signed or encrypted token format containing claims.

Federation: Trust between identity domains that allows one provider to authenticate users for another service.

Credential stuffing: Automated use of breached username-password pairs against other services.

Step-up authentication: Requiring stronger or more recent authentication for a sensitive action.

Review Questions

Short Answer Questions

1. Distinguish authentication from authorization.

2. Why is a unique salt used in password hashing?

3. State the security purposes of the Secure and HttpOnly cookie attributes.

4. What problem does PKCE address in OAuth 2.0?

5. Why should an ID token not normally be sent to an API as an access token?

Long Answer Questions

1. Explain how a secure password lifecycle should address registration, storage, login, reset, and factor recovery.

2. Describe the principal security controls required for browser session management.

3. Compare passwords, TOTP, push authentication, hardware keys, and passkeys.

4. Explain OAuth 2.0 and OpenID Connect, including their roles, tokens, and validation requirements.

5. Analyze the operational and governance risks introduced by federated identity.

Analytical / Application Questions

1. A company stores JWTs in browser local storage and accepts any token with a valid signature, regardless of issuer or audience. Identify the risks and propose a migration plan.

2. An organization introduces account lockout after five failed attempts. Explain how attackers could abuse this policy and design a more balanced defense against password spraying and brute force.

3. A university wants passwordless login but provides email-only recovery for all users. Evaluate the design and recommend a recovery model that preserves the intended assurance level.

22. Multiple Choice Questions with Answers

Question 1

Which statement best distinguishes OAuth 2.0 from OpenID Connect?

A. OAuth 2.0 is an identity protocol, while OpenID Connect is only an encryption protocol.

B. OAuth 2.0 delegates authorization, while OpenID Connect adds authentication and identity claims.

C. OAuth 2.0 is used only for passwords, while OpenID Connect is used only for biometrics.

D. OAuth 2.0 replaces session management, while OpenID Connect replaces authorization.

Correct Answer: B. OAuth 2.0 delegates authorization, while OpenID Connect adds authentication and identity claims.

Question 2

What is the primary purpose of rotating the session identifier after successful login?

A. To increase the password length requirement

B. To prevent session fixation

C. To encrypt the user profile

D. To disable multifactor authentication

Correct Answer: B. To prevent session fixation

Question 3

Which password-storage approach is most appropriate?

A. Plaintext storage in a protected database

B. Reversible encryption using a shared application key

C. A unique salt with Argon2id, scrypt, or bcrypt

D. A fast unsalted SHA-256 hash

Correct Answer: C. A unique salt with Argon2id, scrypt, or bcrypt

Question 4

A public browser application uses OAuth 2.0. Which combination is most appropriate?

A. Authorization Code with PKCE

B. Password grant with a client secret embedded in JavaScript

C. Implicit trust based only on the redirect URL

D. An access token placed in the URL query string

Correct Answer: A. Authorization Code with PKCE

Question 5

Which validation is especially important when an API receives a JWT?

A. Checking only that the token contains a username

B. Checking issuer, audience, signature, and expiry

C. Trusting the algorithm named by the token without restriction

D. Accepting every key reference supplied in the token header

Correct Answer: B. Checking issuer, audience, signature, and expiry

Question 6

Why is a passkey generally more resistant to ordinary phishing than a password?

A. It is always shorter than a password.

B. It uses a public-key credential bound to the legitimate origin.

C. It is stored in every application database.

D. It removes the need for authorization checks.

Correct Answer: B. It uses a public-key credential bound to the legitimate origin.

Question 7

Which cookie configuration provides the strongest general protection for an authentication session?

A. Secure, HttpOnly, and an appropriate SameSite setting

B. Domain set to every domain on the internet

C. Session identifier included in the URL

D. HttpOnly disabled so scripts can manage the session

Correct Answer: A. Secure, HttpOnly, and an appropriate SameSite setting

Question 8

Why can account lockout after a small number of failures be problematic?

A. It prevents password hashing.

B. Attackers can deliberately lock out targeted users.

C. It makes phishing-resistant authentication impossible.

D. It disables token expiration.

Correct Answer: B. Attackers can deliberately lock out targeted users.

Question 9

Which statement about an OIDC ID token is correct?

A. It is always intended for every API in the organization.

B. It is an identity assertion intended for the client that requested authentication.

C. It must be stored permanently in a public browser cookie.

D. It does not require issuer or audience validation.

Correct Answer: B. It is an identity assertion intended for the client that requested authentication.

Question 10

Which design best protects a password-reset process?

A. A predictable link valid for several weeks

B. A reusable link sent through an unencrypted channel

C. A random, single-use, short-lived link with session revocation after reset

D. A reset based only on publicly available security questions

Correct Answer: C. A random, single-use, short-lived link with session revocation after reset

Web Application Security and Secure Coding
Chapter 5 of 14