Authentication, Authorization and Web SecurityIntroductionModern web applications process identities, personal data, financial transactions, and organizational decisions. Security therefore cannot be added as a final feature; it must be designed into the application’s architecture, code, deployment, and operational processes. Authentication answers “Who is the subject?” Authorization answers “What may that subject do?” Web security protects these decisions and the data on which they depend from abuse, error, and misconfiguration. This chapter presents a practical security model for web applications. It explains identity and sessions, tokens and OAuth, role-based access control, common attacks identified in OWASP guidance, secure cryptography, HTTP security headers, threat modeling, and secure implementation practices. Learning ObjectivesAfter studying this chapter, a student should be able to: - distinguish authentication, authorization, accounting, and identity management;
- design secure session and token-based authentication;
- explain OAuth 2.0 and OpenID Connect and select appropriate flows;
- implement role- and permission-based access control;
- identify and mitigate XSS, CSRF, injection, broken access control, and insecure configuration;
- apply password hashing, encryption, secure headers, logging, and threat modeling;
- evaluate security trade-offs in a realistic web application.
1. Identity, Authentication, and AuthorizationAn identity is a representation of a person, organization, service, or device. Authentication verifies a claimed identity. Authorization determines whether an authenticated subject may perform an action on a resource. Accounting, or auditing, records security-relevant activity. A useful conceptual sequence is: - The subject presents evidence, such as a password, passkey, or access token.
- The identity provider validates the evidence.
- The application establishes an authenticated context.
- A policy engine evaluates the requested action and resource.
- The application permits or denies the operation and records the decision.
Authentication factors are commonly classified as: | Factor | Example | Limitation |
|---|
| Knowledge | Password or PIN | Can be guessed, reused, or phished | | Possession | Hardware key or authenticator device | Can be lost or stolen | | Inherence | Fingerprint or face | Difficult to replace if compromised |
Multi-factor authentication combines factors from different categories. Two passwords are not two-factor authentication. Phishing-resistant methods, especially passkeys based on public-key cryptography, are preferable for high-value accounts. The principle of least privilege grants only the permissions required for a task. Separation of duties prevents one identity from controlling an entire sensitive process. Deny-by-default means that an operation is rejected unless an explicit policy permits it. 2. Passwords and Credential LifecyclePasswords should never be stored in plaintext or with reversible encryption. A password-verification system stores a salted, deliberately expensive password hash produced by a password hashing function such as Argon2id, scrypt, or bcrypt. A salt is unique random data stored with the hash; it prevents identical passwords from producing identical stored values and makes precomputed tables less useful. A password hash is not encryption: encryption is designed to be reversed with a key, whereas password hashing is designed to resist reversal. Work factors should be selected through benchmarking and reviewed as hardware changes. A server should also rate-limit attempts and use breached-password screening, while avoiding detailed error messages that reveal whether an account exists. Password reset tokens must be random, short-lived, single-use, and stored securely. They should be invalidated after use or after a password change. Account recovery is part of authentication security and must not be weaker than ordinary login. 3. Sessions and CookiesIn a traditional session architecture, the server maintains session state and gives the browser an unpredictable session identifier. The browser returns that identifier in a cookie on subsequent requests. The identifier must contain no sensitive information and must be generated using a cryptographically secure random generator. Important cookie attributes include: Secure: sends the cookie only over HTTPS;HttpOnly: prevents JavaScript from reading the cookie;SameSite=Lax or Strict: reduces cross-site request transmission;- narrow
Domain and Path: reduce unnecessary exposure; - an appropriate expiration or inactivity timeout.
A session identifier should be rotated after login and privilege changes. This prevents session fixation, in which an attacker causes a victim to use a session identifier known to the attacker. Logout should invalidate the server-side session, not merely delete a browser cookie. Applications should also use idle and absolute session timeouts and re-authentication for high-risk actions. A cookie’s HttpOnly flag helps against token theft through scripts, but it does not stop an attacker from making requests in the victim’s browser if a cross-site scripting vulnerability exists. Defense in depth is therefore necessary. 4. Tokens and Stateless AuthenticationA token is a credential presented by a client to demonstrate an authorization decision or authenticated context. Bearer tokens are dangerous because possession is usually sufficient; they must be protected in transit and at rest. JSON Web Tokens (JWTs) contain a header, a payload, and a signature. A signed JWT provides integrity and issuer authenticity when the algorithm and key are correctly validated. It does not automatically provide confidentiality. Sensitive information should not be placed in a token merely because the token is encoded. JWT validation must check the signature, trusted issuer, intended audience, expiration, not-before time, and acceptable algorithm. The application must not blindly trust an algorithm name supplied by the token. Short-lived access tokens limit the impact of theft. Refresh tokens should be protected more carefully, rotated on use, and revoked when reuse is detected. Token revocation is more difficult in a purely stateless design, so high-risk systems often combine short lifetimes with server-side session or revocation data. | Server session | Access token |
|---|
| State is primarily maintained by the server | Claims may be carried by the token | | Easy central invalidation | Useful for distributed services | | Requires session storage or sharing | Revocation and leakage are challenging | | Commonly sent in secure cookies | Commonly sent in an authorization header |
Tokens do not replace authorization. A valid token may identify a user, but each request still requires a policy decision for the requested resource. 5. OAuth 2.0 and OpenID ConnectOAuth 2.0 is an authorization framework for delegated access. It allows a client to obtain limited access to a resource server on behalf of a resource owner. OAuth is not, by itself, an authentication protocol. OpenID Connect (OIDC) adds an identity layer and is used for login. The major actors are the resource owner, client, authorization server, and resource server. In the Authorization Code flow, the browser is redirected to the authorization server, the user authenticates there, and the client receives a short-lived authorization code. The client exchanges the code for tokens. Proof Key for Code Exchange (PKCE) binds the exchange to the initiating client and is recommended for public clients and modern browser-based applications. The state value protects the authorization response against request forgery and mix-up attacks. OIDC also uses a nonce to bind an identity response to the initiating login request. Redirect URIs should be exact allowlisted values, not arbitrary URLs. Access tokens should be requested with the minimum required scopes. Client secrets must not be embedded in browser or mobile code, where users can extract them. An ID token is intended for the client and should not normally be sent to an API as an access token. The API should validate an access token issued for that API, including its audience and scopes. 6. Authorization ModelsRole-based access control (RBAC) associates permissions with roles and roles with users. For example, an editor may publish articles while a reader may only view them. RBAC is easy to explain and administer, but large systems can suffer from role explosion. Permission checks should occur on the server, at the point where the resource is accessed. Hiding a button in the user interface is not authorization. A request such as /accounts/1042 must be checked against the authenticated user’s permitted account, even if the user changed the number in the URL. Attribute-based access control (ABAC) evaluates attributes of the subject, resource, action, and context. A policy might allow a clinician to view a patient record only when the clinician is assigned to that patient and is on duty. Relationship-based systems evaluate links such as “user is a member of project.” In practice, systems often combine roles with ownership, tenant boundaries, resource state, and contextual conditions. A secure policy should specify subject, action, resource, and constraints. Administrative interfaces must use the same authorization logic as ordinary interfaces. Every sensitive operation should be tested for horizontal escalation (accessing another user’s data) and vertical escalation (performing a higher-privilege action). 7. Threat ModelingThreat modeling is a structured way to anticipate abuse before implementation. A practical process is: - Define the system’s assets, users, trust boundaries, and security objectives.
- Draw data flows between browsers, servers, APIs, databases, queues, and external providers.
- Identify threats using categories such as spoofing, tampering, repudiation, information disclosure, denial of service, and elevation of privilege.
- Rate likelihood and impact.
- Select mitigations and assign owners.
- Reassess when architecture or dependencies change.
A simple risk priority can be expressed as: Risk priority = Likelihood × Impact Here, likelihood and impact are ordinal ratings chosen by the organization, not universal physical units. The multiplication is a prioritization aid rather than a precise probability calculation. It should not be used to ignore a low-frequency catastrophic threat. Threat modeling should include abuse cases: credential stuffing, unauthorized object access, malicious file upload, stolen refresh tokens, and compromised third-party services. Security requirements should then become testable acceptance criteria. 8. Common Web Vulnerabilities and DefensesCross-Site Scripting (XSS)XSS occurs when attacker-controlled content is interpreted as executable script in another user’s browser. Stored XSS persists in application data; reflected XSS is returned in a response; DOM-based XSS arises through unsafe client-side operations. The primary defense is context-sensitive output encoding. HTML text, HTML attributes, URLs, JavaScript, and CSS require different encoders. Framework auto-escaping should remain enabled. Avoid inserting untrusted strings with innerHTML; use safe text APIs or a carefully configured sanitizer when rich text is genuinely required. A Content Security Policy (CSP) can reduce impact but is not a substitute for correct encoding. Cross-Site Request Forgery (CSRF)CSRF abuses automatically attached credentials, especially cookies, to cause a victim’s browser to submit an unwanted state-changing request. Defenses include SameSite cookies, synchronizer tokens, and the double-submit-cookie pattern. State-changing operations should not use GET. A server should validate the expected origin or referer where appropriate and should never rely solely on a hidden form field without server-side validation. InjectionInjection occurs when untrusted data is interpreted as commands or query language. SQL injection is prevented by parameterized queries or safely designed object-relational interfaces. Input validation should constrain type, length, range, and allowed format, but validation alone is not a substitute for parameterization. Shell commands, LDAP, template engines, and NoSQL databases require their own safe APIs and escaping rules. Broken Access ControlBroken access control includes missing checks, insecure direct object references, predictable identifiers treated as authorization, and privilege escalation. Enforce policy server-side, centralize reusable authorization decisions, use deny-by-default, and test each resource and action. Returning a generic not-found response can reduce information leakage, but it must not replace the permission check. Insecure ConfigurationExamples include debug mode in production, default passwords, excessive CORS origins, verbose stack traces, exposed administrative endpoints, weak TLS settings, missing security headers, and unpatched dependencies. Configuration should be versioned, reviewed, environment-specific, and validated at startup. Secrets belong in a managed secret store or protected environment mechanism, not source code or client bundles. 9. Cryptography and Transport SecurityHTTPS provides confidentiality and integrity in transit when TLS is correctly configured and certificates are validated. Applications should use modern TLS configurations, redirect HTTP to HTTPS where appropriate, and enable HTTP Strict Transport Security (HSTS) only after understanding its operational consequences. HSTS instructs compliant browsers to use HTTPS for a domain for a specified period. Encryption at rest protects data if storage is exposed, but key management is the central problem. Keys should be generated by secure mechanisms, separated from encrypted data where feasible, rotated according to policy, and access-controlled. Application-level encryption can protect especially sensitive fields, while database and disk encryption address broader storage threats. Hashing, encryption, signing, and random generation are distinct operations and should use standard libraries rather than custom algorithms. 10. Secure Headers and Browser PolicyUseful response headers include: Content-Security-Policy: restricts permitted content sources and can mitigate XSS;Strict-Transport-Security: requires HTTPS for future browser requests;X-Content-Type-Options: nosniff: reduces MIME-type confusion;Referrer-Policy: limits referrer information leakage;Permissions-Policy: restricts selected browser capabilities;frame-ancestors in CSP: helps prevent clickjacking.
CORS is a browser access-control mechanism, not an authentication system. An API should allow only necessary origins and methods. Wildcard origins are inappropriate when credentials are included. Security headers must be tested against actual application behavior because an overly restrictive policy can break legitimate functions, while a permissive policy provides little protection. 11. Logging, Monitoring, and Incident ResponseSecurity logs should record authentication successes and failures, password resets, authorization denials, administrative changes, token events, and suspicious input. Logs must avoid passwords, access tokens, session identifiers, and unnecessary personal data. They should include time, request correlation identifier, actor or anonymous status, action, outcome, and source context where lawful and useful. Monitoring should detect credential stuffing, unusual geographic or device changes, repeated authorization failures, and token reuse. Logs require integrity protection, controlled access, retention limits, and time synchronization. Incident response includes containment, evidence preservation, notification obligations, credential rotation, recovery, and lessons learned. 12. Illustrative Case: Campus Research PortalBackground. A fictional university research portal allows students to upload project reports, supervisors to review them, and administrators to manage accounts. Problem. The first version stores sessions without rotation, places user identifiers in predictable URLs, accepts rich HTML comments, and uses a broad CORS policy. A supervisor can alter a URL and view another student’s report. Analysis. The predictable URL is not itself the vulnerability; the missing object-level authorization check is. Rich comments create XSS risk. Broad CORS increases the number of origins that may read responses. Failure to rotate the session identifier creates session-fixation risk. Approach. The team adopts secure, rotated cookies; server-side authorization based on role, project membership, and resource ownership; parameterized database queries; a vetted HTML sanitizer for the limited rich-text feature; CSRF tokens for cookie-authenticated state changes; exact CORS allowlists; CSP and other security headers; rate limiting; and structured audit logs. Threat modeling is repeated after the design change. Automated tests attempt both horizontal and vertical privilege escalation. Outcome. Students can access only their own projects, supervisors can access assigned projects, and administrators can manage accounts without receiving unnecessary academic content. Security controls are documented as requirements and checked in continuous integration. Learning points. Identity, authorization, browser defenses, configuration, and monitoring must work together. A secure interface is not evidence of a secure API, and a valid login does not justify every data access. 13. Professional Practice and GovernanceSecurity involves privacy, accessibility, accountability, and legal duties. Collect only necessary identity data, state the purpose of collection, limit retention, and provide appropriate user rights under applicable privacy law and institutional policy. Access decisions should be explainable to administrators and, where relevant, affected individuals. Dependencies, frameworks, identity providers, and cloud services create supply-chain risk. Maintain an inventory, pin and update dependencies, verify advisories, review transitive packages, and define ownership for vulnerabilities. Security testing should include code review, dependency scanning, dynamic testing, abuse-case tests, and periodic independent assessment. Automated tools are valuable but cannot understand every business authorization rule. Artificial intelligence can assist with log triage, code analysis, and test generation, but generated code may contain insecure assumptions, leak sensitive data to external services, or incorrectly implement authorization. Human review, data governance, reproducible testing, and least-privilege tool access remain necessary. Challenges and LimitationsNo single control eliminates risk. MFA can be bypassed through phishing or recovery abuse; CSP can be weakened by unsafe exceptions; JWTs can be valid but wrongly authorized; and encryption cannot protect data after a legitimate application process has disclosed it. Security controls also create usability, availability, and maintenance costs. Decisions should therefore be risk-based, documented, tested, and revisited as threats and business requirements change. Best-Practice Checklist- Use HTTPS and secure, modern TLS configurations.
- Hash passwords with a suitable adaptive password-hashing function and unique salts.
- Rotate and invalidate sessions after authentication and privilege changes.
- Protect cookies with Secure, HttpOnly, and suitable SameSite settings.
- Validate tokens, issuer, audience, signature, lifetime, and scope.
- Use OAuth Authorization Code with PKCE and OIDC for delegated login.
- Enforce authorization on every sensitive server-side operation.
- Parameterize queries and encode output for its context.
- Use CSRF defenses for cookie-authenticated state changes.
- Apply restrictive, tested CORS and security headers.
- Store secrets outside source code and remove debug features from production.
- Log security events without recording credentials or tokens.
- Threat-model new features and test abuse cases continuously.
Chapter SummaryAuthentication establishes identity, while authorization determines permitted actions on resources. Secure applications use strong password hashing, phishing-resistant MFA where practical, protected and rotated sessions, carefully validated tokens, and OAuth 2.0 with PKCE and OIDC for delegated identity. RBAC is useful, but resource ownership, tenant boundaries, attributes, and context must also be considered. XSS requires contextual output encoding and safe DOM practices; CSRF requires browser-aware defenses; injection requires parameterized interfaces; broken access control requires server-side, deny-by-default policy checks; and insecure configuration requires controlled deployment practices. HTTPS, encryption, secure headers, logging, monitoring, threat modeling, privacy governance, and tested incident response provide additional layers. Security is a continuous engineering responsibility rather than a one-time feature. Key TermsAuthentication: Verification of a claimed identity. Authorization: Decision about permitted actions on resources. Access token: Credential presented to access a protected resource. Adaptive password hash: Deliberately expensive password-derived value. CSRF: Attack that induces a browser to make an unwanted authenticated request. CORS: Browser policy controlling cross-origin access to responses. CSP: Policy restricting content sources and browser execution behavior. JWT: Signed or encrypted JSON-based token format. Least privilege: Granting only necessary permissions. MFA: Authentication using multiple independent factor categories. Nonce: Unique value used to bind a protocol response to a request. OAuth 2.0: Framework for delegated authorization. OIDC: Identity layer built on OAuth 2.0. RBAC: Authorization model associating permissions with roles. Session fixation: Attack involving a session identifier known before login. Threat modeling: Structured identification and mitigation of security threats. XSS: Injection of executable content into a user’s browser. Zero trust: Approach that continuously verifies access rather than trusting network location. Review QuestionsShort Answer Questions- Distinguish authentication from authorization.
- Why should passwords be hashed rather than encrypted?
- State three important cookie security attributes.
- What problem does PKCE address?
- Why is input validation alone insufficient against SQL injection?
Long Answer Questions- Explain the lifecycle of a secure server-side session.
- Compare RBAC and ABAC, including situations in which each is appropriate.
- Describe OAuth 2.0 Authorization Code flow with PKCE and OIDC.
- Explain the causes and defenses of XSS, CSRF, and broken access control.
- Develop a threat model for a web-based student information system.
Analytical / Application Questions- A logged-in user changes
/invoice/301 to /invoice/302 and sees another customer’s invoice. Identify the vulnerability, explain why random identifiers alone do not solve it, and propose server-side controls. - An API accepts requests from every origin and uses cookies for authentication. Analyze the risks and design a safer CORS and CSRF configuration.
- A team proposes long-lived JWTs containing user roles and storing them in browser local storage. Critically evaluate the proposal and recommend a safer design.
Multiple Choice Questions with AnswersQuestion 1Which statement best distinguishes authentication from authorization? A. Authentication determines permissions, while authorization verifies passwords. B. Authentication verifies identity, while authorization determines permitted actions. C. Authentication encrypts data, while authorization compresses data. D. Authentication logs events, while authorization deletes sessions. Correct Answer: B. Authentication verifies identity, while authorization determines permitted actions. Question 2Which cookie attribute prevents client-side JavaScript from reading the cookie? A. Secure B. SameSite C. HttpOnly D. Domain Correct Answer: C. HttpOnly Question 3What is the primary purpose of a unique password salt? A. To make the password reversible B. To prevent identical passwords from producing identical stored hashes C. To transmit passwords over HTTP safely D. To replace multi-factor authentication Correct Answer: B. To prevent identical passwords from producing identical stored hashes Question 4Which OAuth mechanism binds an authorization-code exchange to the client that initiated it? A. CSP B. PKCE C. HSTS D. RBAC Correct Answer: B. PKCE Question 5What is the strongest general defense against SQL injection? A. Hiding database error messages only B. Using predictable numeric identifiers C. Using parameterized queries D. Encoding all passwords with Base64 Correct Answer: C. Using parameterized queries Question 6A user accesses another user’s record by changing an identifier in a URL. What is the principal issue? A. Broken object-level authorization B. TLS certificate expiry C. MIME-type confusion D. Password hashing cost Correct Answer: A. Broken object-level authorization Question 7Which statement about a signed JWT is correct? A. A signature automatically makes its contents confidential. B. A valid signature eliminates the need for authorization checks. C. The recipient should validate claims such as issuer, audience, and expiry. D. The algorithm specified in the token should always be accepted without restriction. Correct Answer: C. The recipient should validate claims such as issuer, audience, and expiry. Question 8Which practice most directly mitigates CSRF for cookie-authenticated state changes? A. Using GET for every operation B. Adding server-validated CSRF tokens C. Disabling database indexes D. Displaying fewer interface buttons Correct Answer: B. Adding server-validated CSRF tokens Question 9Which header mechanism can restrict the sources from which browser content may load? A. Content-Security-Policy B. Content-Length C. Accept-Language D. Date Correct Answer: A. Content-Security-Policy Question 10In threat modeling, what does a trust boundary represent? A. A point where data or control moves between different trust levels B. The maximum password length C. A database sorting rule D. A browser’s screen boundary Correct Answer: A. A point where data or control moves between different trust levels
|