Authentication, Security and PrivacyIntroductionA full-stack application is trustworthy only when it protects the identities, data, and actions of its users. Authentication establishes who a user is; authorization determines what that user may do; security protects the application from misuse and attack; and privacy governs how personal information is collected, processed, stored, and shared. These concerns apply across the browser, mobile client, API, server, database, cloud infrastructure, and development process. Security is not a feature added at the end of development. It is a system property produced by design decisions, implementation practices, configuration, monitoring, and organizational controls. A technically correct login form can still be insecure if passwords are stored in plaintext, sessions do not expire, authorization is checked only in the interface, or sensitive data is unnecessarily collected. This chapter presents practical foundations for implementing authentication and authorization, handling credentials securely, reducing common OWASP risks, applying encryption and least privilege, and integrating privacy and secure coding into full-stack development. Learning ObjectivesBy the end of this chapter, you should be able to: - Distinguish authentication, authorization, accounting, security, and privacy.
- Explain session-based and token-based authentication.
- Design secure password storage and credential-recovery processes.
- Apply role-based access control and server-side authorization checks.
- Identify and mitigate common web application risks.
- Select suitable uses of hashing, encryption, TLS, and digital signatures.
- Apply least privilege, secure defaults, input validation, and output encoding.
- Recognize privacy obligations and ethical responsibilities in application development.
- Evaluate a security design through threat modelling and practical testing.
1. The Security Model of a Full-Stack Application1.1 Authentication, authorization, and accountingAuthentication answers, “Who are you?” It may use a password, a passkey, a one-time code, a hardware token, or biometric verification. Authentication should establish an identity with an appropriate level of confidence. Authorization answers, “What may this authenticated identity do?” For example, a customer may view their own invoices, while an administrator may approve refunds. Authorization must be enforced by trusted server-side code, not merely by hiding buttons in a web page. Accounting, often called auditing or accountability, records relevant actions: which identity performed an operation, when it occurred, what resource was affected, and whether the operation succeeded. Logs should support investigation without exposing passwords, access tokens, or unnecessary personal information. These functions are related but not interchangeable. A valid login does not grant unrestricted access. Conversely, an authorization decision should not be made for an identity that has not been authenticated. 1.2 The security objectivesA useful foundation is the CIA triad: - Confidentiality: only authorized parties can access information.
- Integrity: information and operations are not altered improperly.
- Availability: legitimate users can access services when needed.
Applications also require authenticity, accountability, resilience, and privacy. A service can preserve confidentiality but fail availability through denial-of-service, or preserve availability while allowing unauthorized modification. Security engineering therefore requires balancing risks rather than pursuing one objective in isolation. 1.3 Assets, threats, vulnerabilities, and risksAn asset is something valuable, such as a user account, payment record, API key, or service reputation. A threat is a potential harmful event, such as credential theft. A vulnerability is a weakness that makes exploitation possible, such as SQL injection. Risk combines the possibility of an adverse event with its impact. Threat modelling begins by identifying trust boundaries and asking: - What must be protected?
- Who might attack it, and what capabilities do they have?
- Where does untrusted input enter?
- What happens if a control fails?
- How will an incident be detected and contained?
The STRIDE categories—spoofing, tampering, repudiation, information disclosure, denial of service, and elevation of privilege—provide one practical way to structure these questions. Threat modelling is not a guarantee of security; it is a disciplined method for finding design weaknesses before deployment. 2. Sessions and Tokens2.1 Session-based authenticationIn a traditional session design, the server authenticates a user and creates a session record. The browser receives an opaque session identifier, normally in a cookie. On each request, the browser sends the cookie, and the server retrieves the session data. A secure session cookie should normally use: - Secure, so it is sent only over HTTPS.
- HttpOnly, so ordinary JavaScript cannot read it.
- SameSite, to reduce cross-site request risks; the appropriate value depends on the application’s cross-site requirements.
- A narrow Path and suitable expiration where practical.
The session identifier should be generated with a cryptographically secure random generator, be sufficiently long, and never contain personal information. The identifier should be rotated after login and privilege changes to reduce session fixation risk. Sessions should expire after an appropriate period of inactivity and, for sensitive applications, after an absolute lifetime as well. The server must invalidate a session on logout. Clearing a browser cookie alone is insufficient if a stolen server-side session remains valid. 2.2 Token-based authenticationA token is a credential presented to an API. A bearer token grants access to whoever possesses it, so its disclosure is serious. Access tokens should be short-lived, transmitted only through protected channels, and stored in a manner appropriate to the client architecture. A signed JSON Web Token (JWT) can contain claims such as issuer, subject, audience, expiration, and scopes. A signature provides integrity and authenticity of the token’s contents; it does not automatically provide confidentiality. Sensitive information should not be placed in a token merely because it is encoded. Token verification must check the expected algorithm, issuer, audience, signature, and expiration rather than trusting claims supplied by the client. Refresh tokens are longer-lived credentials used to obtain new access tokens. They require stronger protection, rotation, revocation, and monitoring. A common design stores refresh tokens in a secure, HttpOnly cookie and keeps a server-side record, ideally storing a hash of the token rather than the raw value. 2.3 Comparing the approaches| Consideration | Server session | Access token | Refresh-token design |
|---|
| State | Usually stored on server | Often self-contained | Server record is recommended | | Revocation | Straightforward | More difficult until expiry | Practical through rotation and records | | Browser risk | Cookie and CSRF concerns | Token theft and storage concerns | Cookie protection and rotation required | | Typical use | Browser applications | APIs and distributed services | Long-lived login with short-lived access | | Main design issue | Session fixation and CSRF | Validation and leakage | Replay, theft, and revocation |
Neither approach is universally superior. A server session is often simpler for a browser-based application. Tokens can be useful across services, but they increase the consequences of token leakage and require careful validation. 2.4 Cross-site request forgeryCross-site request forgery (CSRF) occurs when a browser automatically sends authentication credentials with a request initiated by an attacker-controlled site. It is particularly relevant to cookie-based authentication. Defences include SameSite cookies, unpredictable CSRF tokens tied to the user session, checking trusted origins where appropriate, and requiring deliberate user interaction for high-impact operations. Changing state through GET requests should be avoided. A CSRF token is not a replacement for authorization: it proves that the request came through an expected interaction pattern, not that the requested operation is permitted. 3. Passwords and Credential Handling3.1 Password storagePasswords must never be stored as plaintext or encrypted with a reversible key for routine verification. Instead, the server stores a password hash produced by a password-specific, deliberately expensive algorithm such as Argon2id, scrypt, or bcrypt. During login, the submitted password is processed using the stored parameters and compared using the algorithm’s verification function. A unique salt is generated for each password. The salt prevents identical passwords from producing identical stored values and makes precomputed rainbow tables less useful. The salt is not a secret and is normally stored with the hash. Fast general-purpose hashes such as SHA-256 are not suitable alone for password storage because attackers can test enormous numbers of guesses quickly. Password hashing parameters must be tuned on the deployment hardware, reviewed periodically, and upgraded through rehashing when users log in. A pepper is an additional secret held separately from the database, often in a secrets manager. It can provide defence in depth, but it does not replace a suitable password-hashing algorithm or good secret management. 3.2 Password policy and recoveryA useful policy permits long passphrases, rejects known-compromised passwords, avoids unnecessary composition rules that encourage predictable substitutions, and applies rate limiting. Password managers should be supported. Login errors should not reveal whether an account exists. Password-reset links should contain a cryptographically random, single-use, short-lived token. The token should be transmitted only over HTTPS and stored server-side as a hash where feasible. After a reset, existing sessions and refresh tokens should normally be revoked, and the user should be notified. Security questions based on public facts are weak recovery mechanisms. 3.3 Multi-factor authenticationMulti-factor authentication combines different factor categories: - Something the user knows, such as a password.
- Something the user has, such as a hardware security key.
- Something the user is, such as a biometric characteristic.
Two passwords are not two independent factors. Phishing-resistant methods, particularly passkeys based on public-key cryptography, provide strong protection against credential replay and phishing. One-time codes improve security over passwords alone, but SMS codes can be exposed through account takeover of a telephone number and should not be treated as the strongest option. 4. Authorization and Least Privilege4.1 Authorization modelsRole-based access control (RBAC) assigns permissions through roles such as customer, support agent, and administrator. It is understandable and suitable for many systems, but role proliferation can become difficult to manage. Attribute-based access control (ABAC) evaluates attributes of the subject, resource, action, and context. For example, an employee may edit a document only if they belong to its department, the document is not archived, and the request originates from an approved environment. Discretionary access control allows resource owners to grant access, while mandatory access control applies centrally enforced classifications and policies. A system may combine these models. 4.2 Server-side object authorizationA frequent vulnerability is insecure direct object reference or broken object-level authorization. An API such as /api/orders/4821 must verify that the authenticated user is allowed to access order 4821. It is not enough to infer permission from the fact that the user knows the identifier or that the interface did not display the order. A secure authorization check should consider the requested action, the authenticated subject, the target resource, and relevant business rules. Deny-by-default is safer than granting access and attempting to remove exceptions later. Administrative endpoints should have separate controls, stronger authentication, and detailed audit logging. 4.3 Least privilege and separation of dutiesLeast privilege gives each identity only the access required for its tasks, for only as long as necessary. Database application accounts should not normally be database administrators. A support user who can view customer information need not delete it. Development, testing, and production credentials should be separate. Separation of duties reduces the possibility that one compromised or dishonest identity can complete a high-risk process alone. For example, one employee may prepare a refund while another approves it. Privileges should be reviewed, removed promptly when roles change, and tested with negative authorization cases. 5. Common Application Risks and Defences5.1 InjectionInjection occurs when untrusted data is interpreted as commands or queries. SQL injection is prevented primarily through parameterized queries or safe ORM APIs, not by manually escaping strings. Command injection requires avoiding shell execution where possible and using structured process APIs when it is unavoidable. Input validation should enforce type, length, range, and allowed format. Validation improves reliability and reduces attack surface, but it is not a substitute for parameterization. A robust design treats all client input as untrusted, including hidden fields, headers, cookies, and values received from other services. 5.2 Cross-site scriptingCross-site scripting (XSS) occurs when attacker-controlled content is executed as script in another user’s browser. Context-aware output encoding is the primary defence: HTML, attribute, URL, and JavaScript contexts have different escaping rules. Framework auto-escaping should remain enabled. Dangerous HTML insertion should be avoided or performed only through a well-tested sanitizer. A Content Security Policy can reduce the impact of XSS by restricting script sources, but it is a defence in depth measure rather than a replacement for safe output handling. HttpOnly cookies reduce the ability of injected scripts to steal cookies, but they do not prevent an attacker from performing actions through the victim’s browser. 5.3 Security misconfiguration and vulnerable componentsSecure configuration includes disabling debug output in production, removing default accounts, limiting administrative interfaces, setting appropriate headers, patching dependencies, and separating secrets from source code. Dependency inventories and automated vulnerability scanning are useful, but every alert requires contextual evaluation. Secrets should be supplied through a secrets manager or protected environment configuration. They should not be committed to a repository, embedded in client-side bundles, or printed in logs. Rotation must be possible without rebuilding an entire system unnecessarily. 5.4 Cryptographic failuresUse TLS for data in transit and authenticated encryption for sensitive data at rest when the threat model requires it. Encryption keys must be managed separately from encrypted data, with access control, rotation, backup, and recovery procedures. Hashing, encryption, and encoding are different: - Hashing is a one-way transformation used for integrity checks and password verification.
- Encryption is reversible with a key and provides confidentiality.
- Encoding changes representation and provides no security by itself.
- Digital signatures provide integrity, authenticity, and non-repudiation properties under appropriate assumptions; they do not by themselves hide content.
Use established, maintained cryptographic libraries and authenticated encryption modes such as AES-GCM or ChaCha20-Poly1305 where appropriate. Do not design a novel cipher or reuse a nonce where the selected algorithm forbids reuse. 5.5 SSRF, file risks, and unsafe deserializationServer-side request forgery (SSRF) occurs when an attacker causes the server to make requests to unintended destinations, potentially reaching internal services or cloud metadata endpoints. Defences include allowlisting destinations, restricting protocols and redirects, validating resolved addresses, applying network egress controls, and avoiding direct access to internal metadata services. File upload controls should restrict type, size, and storage location; generate server-side names; scan where appropriate; and prevent uploaded content from being executed. Unsafe deserialization can allow attacker-controlled data to create objects or execute code. Prefer simple, schema-validated data formats and safe parsers. 6. Privacy by DesignSecurity protects information from unauthorized activity; privacy also asks whether the information should be collected, how it is used, and whether individuals have meaningful control. Privacy by design includes: - Data minimization: collect only what is necessary.
- Purpose limitation: use data for specified legitimate purposes.
- Retention limitation: delete or anonymize data when it is no longer needed.
- Transparency: explain collection and use in understandable language.
- User control: support applicable access, correction, deletion, and consent choices.
- Privacy-enhancing defaults: avoid making broad sharing the default.
Legal requirements vary by jurisdiction. Developers should work with organizational privacy and legal specialists regarding applicable frameworks, such as data-protection legislation, sector-specific rules, and contractual obligations. A privacy notice is not a substitute for lawful processing, sound security, or ethical judgment. Personal data can appear in logs, analytics, backups, error reports, and test datasets. Production data should not be copied casually into development. Logs should use identifiers or redaction where possible, while retaining enough information for incident investigation. Anonymization claims should be tested carefully because combining datasets can enable re-identification. 7. Secure Development and OperationsSecurity should be integrated into the software development life cycle: - Define security and privacy requirements.
- Model threats and trust boundaries.
- Implement using secure frameworks and coding standards.
- Review code and dependencies.
- Test authentication, authorization, validation, and failure paths.
- Deploy with hardened configuration.
- Monitor, respond to incidents, patch, and learn.
Automated tests should include negative cases: a user accessing another user’s resource, an expired token, a malformed identifier, a missing CSRF token, and a revoked session. Dynamic testing, dependency scanning, secret scanning, and penetration testing complement—not replace—design review and human reasoning. Errors shown to users should be useful but not disclose stack traces, database details, secrets, or internal network information. Internally, logs should be structured, access-controlled, time-synchronized, and protected against tampering. Alerting should identify unusual login rates, privilege changes, token reuse, and suspicious administrative actions. Incident response normally includes preparation, detection, analysis, containment, eradication, recovery, notification where required, and post-incident improvement. Backups must be protected and restoration must be tested; a backup that cannot be restored is not a reliable recovery control. 8. Illustrative Case: Securing a Community Clinic PortalBackgroundA small clinic operates a portal through which patients view appointments and clinicians record notes. The first version uses email and password login, a browser cookie, and REST endpoints for patient records. ProblemA security review finds that passwords were stored using a fast hash without unique salts, the session identifier was not rotated after login, and an endpoint allowed any logged-in user to request a record by numeric identifier. Error responses also revealed whether an email address was registered. Development used a copy of production data. AnalysisThe portal contains highly sensitive personal and health information. The most serious risks are account compromise, broken object-level authorization, session fixation, and privacy exposure in development. The clinic also needs reliable audit records because unauthorized access to clinical notes has significant consequences. Approach and solutionThe team adopts Argon2id through a maintained library, with a unique salt and parameters tested on production-equivalent hardware. Existing passwords are upgraded after successful login and reset where necessary. Login and password-reset attempts are rate-limited, and multi-factor authentication is offered to clinicians. The server creates a random session identifier, rotates it after authentication, sets Secure, HttpOnly, and appropriate SameSite attributes, and expires inactive sessions. Logout invalidates the server-side session. Every record request performs a server-side authorization check based on the patient-clinician relationship; numeric identifiers are treated as references, not permissions. The team introduces CSRF protection for state-changing cookie-authenticated requests, generic account-recovery messages, parameterized database queries, and structured audit logs that exclude passwords and session values. A synthetic dataset replaces production data in development. Access to production is restricted through separate accounts and least-privilege database permissions. OutcomeThe portal no longer relies on identifier secrecy, and compromised browser state has a shorter useful lifetime. Clinical access can be investigated through audit records, while development no longer exposes real patient information. The controls do not eliminate all risk, but they reduce the probability and impact of common failures. Learning points- Authentication is only one part of access control.
- Sensitive systems require privacy controls throughout the data life cycle.
- Secure defaults and framework-supported controls reduce implementation error.
- Authorization tests should attempt access to resources belonging to other users.
- Security improvements are ongoing because threats, dependencies, and requirements change.
9. Limitations and Professional JudgementNo single control prevents every attack. MFA can be defeated through social engineering; encryption does not help if an authorized application is compromised; a WAF cannot correct flawed authorization logic; and a privacy notice cannot justify excessive collection. Controls must be selected according to assets, threat actors, impact, regulatory context, usability, and cost. AI-assisted coding can help identify patterns, generate tests, and explain APIs, but generated code may contain insecure assumptions, vulnerable dependencies, or incorrect cryptographic use. Developers remain responsible for reviewing code, checking documentation, testing security properties, and protecting confidential data from being sent to external tools. AI should support—not replace—threat modelling and professional accountability. Best-Practice Checklist- Use HTTPS throughout production and protect cookies and tokens.
- Store passwords with Argon2id, scrypt, or bcrypt through a reputable library.
- Rotate sessions after login and privilege changes; revoke them on logout.
- Enforce authorization on every protected server-side operation.
- Use parameterized queries and context-aware output encoding.
- Apply CSRF protection where browser credentials are automatically sent.
- Keep secrets out of source code, client bundles, and logs.
- Minimize personal data, restrict retention, and protect test data.
- Apply least privilege to users, services, databases, and deployment pipelines.
- Log security-relevant events without recording credentials or unnecessary personal data.
- Patch dependencies and test recovery, revocation, and incident procedures.
Chapter SummaryAuthentication establishes identity, authorization governs permitted actions, and accounting supports accountability. Browser applications commonly use server-side sessions, while APIs may use short-lived access tokens and carefully managed refresh tokens. Both approaches require secure transport, expiration, validation, and revocation strategies. Passwords must be protected with salted, deliberately expensive password-hashing algorithms. MFA, secure recovery, rate limiting, and phishing-resistant credentials further reduce account takeover. Authorization must be enforced on the server, use deny-by-default rules, and apply least privilege to people, services, and data. Common risks include injection, XSS, CSRF, broken object-level authorization, cryptographic failures, SSRF, unsafe file handling, and security misconfiguration. Parameterized queries, output encoding, secure cookies, authenticated encryption, safe libraries, dependency management, and threat modelling provide practical defences. Privacy requires minimization, purpose limitation, retention control, transparency, and responsible handling of data in logs, backups, analytics, testing, and AI tools. Secure development is continuous: requirements, design, implementation, testing, deployment, monitoring, incident response, and improvement must work together. Key TermsAuthentication: Verification of a claimed identity. Authorization: Decision about which actions or resources an identity may access. Session: Server-managed state associated with an authenticated client. Access token: Credential presented to access a protected service. Refresh token: Longer-lived credential used to obtain new access tokens. Salt: Unique non-secret value used with a password hash. Password hash: One-way, computationally expensive representation used to verify a password. Multi-factor authentication: Authentication using two or more independent factor categories. RBAC: Access control based on assigned roles. ABAC: Access control based on subject, resource, action, and contextual attributes. Least privilege: Granting only the access necessary for a task. CSRF: Abuse of automatically supplied browser credentials through a forged request. XSS: Injection of content that executes as script in another user’s browser. SQL injection: Manipulation of a database query through untrusted input. TLS: Protocol providing authenticated, encrypted communication over a network. Encryption: Reversible transformation that protects confidentiality using a key. Digital signature: Cryptographic evidence of integrity and signer authenticity. Threat modelling: Structured analysis of assets, trust boundaries, threats, and controls. Data minimization: Collecting and retaining only data necessary for a stated purpose. Security audit: Examination of controls, events, and configurations for weaknesses or compliance. Review QuestionsShort Answer Questions- What is the difference between authentication and authorization?
- Why should password hashes use a unique salt?
- State two important protections for a session cookie.
- What does least privilege mean?
- Why is encoding not equivalent to encryption?
Long Answer Questions- Compare server-side sessions with token-based authentication, including their main risks and suitable use cases.
- Explain how a full-stack application should handle password creation, login, reset, and revocation.
- Describe how RBAC and ABAC differ and give an example of each.
- Explain the relationship between input validation, parameterized queries, and output encoding.
- Discuss privacy by design across collection, storage, use, logging, testing, and deletion.
Analytical / Application Questions- An API allows a logged-in customer to request any invoice by its numeric identifier. Analyse the vulnerability and propose server-side controls and tests.
- Design a session and authorization strategy for a browser-based online examination system with students, invigilators, and administrators.
- A development team wants to paste production logs into an AI coding assistant to diagnose an error. Evaluate the privacy and security risks and recommend a safer workflow.
Multiple Choice Questions with AnswersQuestion 1Which statement best distinguishes authentication from authorization? A. Authentication determines identity; authorization determines permitted actions. B. Authentication encrypts data; authorization hashes passwords. C. Authentication records events; authorization creates backups. D. Authentication validates input; authorization compresses responses. Correct Answer: A. Authentication determines identity; authorization determines permitted actions. Question 2Why is a fast general-purpose hash such as SHA-256 alone unsuitable for password storage? A. It cannot represent text passwords. B. It is designed to be difficult to compute for every use. C. Attackers can test guesses very quickly with it. D. It requires passwords to be sent in plaintext. Correct Answer: C. Attackers can test guesses very quickly with it. Question 3Which cookie attribute helps prevent client-side JavaScript from reading a session cookie? A. Secure B. HttpOnly C. SameSite D. Path Correct Answer: B. HttpOnly Question 4What is the primary purpose of a CSRF token? A. To encrypt a database connection B. To prove that a password is strong C. To help distinguish an expected state-changing request from a forged one D. To replace server-side authorization Correct Answer: C. To help distinguish an expected state-changing request from a forged one Question 5Which practice is the appropriate primary defence against SQL injection? A. Hiding database error messages only B. Using parameterized queries C. Changing numeric IDs to longer numbers D. Encoding the entire database Correct Answer: B. Using parameterized queries Question 6A signed JWT primarily provides which property, assuming its signature is correctly verified? A. Confidentiality of all claims B. Integrity and authenticity of the token contents C. Automatic revocation before expiration D. Protection against every form of XSS Correct Answer: B. Integrity and authenticity of the token contents Question 7Which example best demonstrates least privilege? A. Giving every employee administrator access for convenience B. Allowing an application account only the database operations it requires C. Using one shared account for all services D. Keeping inactive accounts permanently enabled Correct Answer: B. Allowing an application account only the database operations it requires Question 8A user changes the URL from /orders/100 to /orders/101 and sees another customer’s order. What is the central flaw? A. Broken object-level authorization B. Weak compression C. Insufficient HTML styling D. A missing database index only Correct Answer: A. Broken object-level authorization Question 9Which practice best supports privacy by design? A. Collecting all potentially useful data indefinitely B. Copying production personal data into development C. Collecting only data necessary for a specified purpose D. Putting personal data into verbose public error messages Correct Answer: C. Collecting only data necessary for a specified purpose Question 10What is true of encoding compared with encryption? A. Encoding changes representation but does not provide confidentiality by itself. B. Encoding always requires a secret key. C. Encryption is reversible without a key, while encoding is not. D. Encoding provides authenticated integrity in every context. Correct Answer: A. Encoding changes representation but does not provide confidentiality by itself.
|