Chapter 3
Credentials, Passwords, and Account Security
Bachelors Program in Full Stack Development
Authentication & Authorization
•
Bachelor
Credentials, Passwords, and Account Security
Introduction
Authentication establishes that a user, service, or device is associated with a claimed identity. In a full-stack application, authentication commonly begins with a credential such as a username and password, but secure authentication is more than checking whether two strings match. Credentials must be collected, transmitted, stored, recovered, monitored, and revoked without creating unnecessary opportunities for attack.
Passwords remain widely used because they are inexpensive and familiar. They are also vulnerable to guessing, reuse, phishing, database theft, malware, and social engineering. A secure system therefore treats a password as a verifier input rather than as a secret that the application should be able to recover. The central design principle is simple: the system should verify a password without storing the password itself.
This chapter develops the engineering principles needed to implement secure password storage, adaptive hashing, account recovery, rate limiting, lockout, breached-password screening, and defenses against credential stuffing, brute force, phishing, and account enumeration.
Learning Objectives
By the end of this chapter, you should be able to:
distinguish authentication, authorization, identification, and accounting;
explain why passwords must be salted and stored using adaptive password-hashing algorithms;
design a secure registration and login workflow;
compare brute force, credential stuffing, phishing, and password-spraying attacks;
apply rate limiting, progressive delays, monitoring, and carefully designed lockout policies;
implement secure account recovery and password-reset flows;
reduce information leakage through enumeration-resistant responses;
evaluate breached-password screening and password-policy decisions;
analyze the ethical, privacy, operational, and regulatory implications of account security.
1. The Credential Security Problem
A credential is evidence used to authenticate an identity. Examples include a password, a hardware security key, a cryptographic certificate, or a one-time code. Authentication factors are often classified as:
Factor
Meaning
Example
Knowledge
Something the user knows
Password or PIN
Possession
Something the user has
Security key or authenticator device
Inherence
Something the user is
Fingerprint or facial characteristic
Location or context
Evidence about circumstances
Trusted network or device-risk signal
A password alone is a single-factor credential. Multi-factor authentication (MFA) combines independent factors. Two passwords are not two independent factors because both are knowledge factors. MFA can substantially reduce the consequences of password theft, although it does not eliminate phishing, session theft, recovery abuse, or social engineering.
Four terms should be separated:
Identification: claiming an identity, such as entering an email address.
Authentication: verifying the claim.
Authorization: deciding what an authenticated identity may do.
Accounting or auditing: recording security-relevant activity.
A successful password check authenticates a user; it does not authorize every action in the application.
Threat model
A sound design begins by identifying adversaries and assets. Relevant assets include password verifiers, reset tokens, sessions, personal information, payment data, and administrative functions. Threats include:
Online guessing: repeated attempts against a live login endpoint.
Offline cracking: an attacker obtains password hashes and guesses locally.
Credential stuffing: automated use of username-password pairs stolen from another service.
Password spraying: trying a small number of common passwords across many accounts.
Phishing: deceiving users into submitting credentials to an attacker-controlled site.
Enumeration: discovering whether an account exists through messages, timing, or behavior.
Recovery abuse: taking over an account through weak reset procedures.
Malware and session theft: stealing credentials, cookies, or authentication codes from a device.
The most important distinction is between online and offline attacks. Online attempts are constrained by the application's network and policy controls. Offline attacks are constrained mainly by the cost of the password-hashing function and the attacker's computing resources.
2. Password Storage: Hashing, Salting, and Verification
Hashing is not encryption
Encryption is reversible with a key. Hashing is intended to be one-way: a password is transformed into a verifier from which the original password should not feasibly be recovered. A password database should therefore store a password-hash record, not plaintext and not a reversible encrypted copy.
A secure password verifier has three properties:
One-wayness: recovering the password from the verifier is computationally impractical.
Salt uniqueness: identical passwords used by different accounts produce different records.
Cost adjustment: verification can be made deliberately expensive as hardware improves.
Cryptographic hash functions such as SHA-256 are excellent for integrity and digital signatures, but their speed is a disadvantage for password storage. An attacker can compute enormous numbers of guesses with fast general-purpose or specialized hardware. Password storage requires a dedicated, deliberately expensive password-hashing function.
Salts
A salt is a unique, randomly generated value stored with the password-hash record. It is not required to be secret. Conceptually, the stored record contains:
record = algorithm || parameters || salt || verifier
where || denotes concatenation or structured encoding. During verification, the supplied password is processed with the same algorithm, parameters, and salt, and the result is compared with the stored verifier.
Salts prevent precomputed rainbow tables from being directly useful and ensure that two users with the same password do not have identical stored values. A salt does not make a weak password strong and does not replace an adaptive hash.
Use a cryptographically secure random-number generator for salts. Do not use usernames, email addresses, timestamps, or predictable counters as salts. Modern password-hashing libraries usually generate and encode salts automatically.
Adaptive password hashing
An adaptive password hash has a configurable work factor. The application deliberately spends time and, for some algorithms, memory during each verification. The objective is not to make authentication unusable; it is to make large-scale offline guessing expensive.
Common choices include:
Argon2id: generally preferred for new systems because it can impose both time and memory costs and is designed to resist several classes of attacks.
scrypt: memory-hard and suitable where a well-maintained implementation is available.
bcrypt: widely deployed and still useful, but has a limited input-length behavior in many implementations and does not provide the same memory-hard design as Argon2id.
PBKDF2: standardized and widely supported; useful where compliance or platform support requires it, particularly with a strong iteration count and an approved construction.
Use a reputable, maintained library rather than implementing an algorithm yourself. Store the algorithm identifier and parameters with each record so that parameters can be changed and old records can be upgraded after successful login.
A simplified cost model is:
Ctotal ≈ N × Cverify
Here, Ctotal is the attacker’s total computational cost for N guesses, and Cverify is the cost of one verification. This is an approximation: real cost also depends on parallelism, hardware, memory bandwidth, implementation, and attack strategy. It explains why increasing verification cost increases the work of offline cracking, but it does not produce a security guarantee by itself.
For memory-hard algorithms, an additional practical consideration is memory consumption. If each verification requires M bytes of memory and an attacker runs p operations concurrently, approximate working memory is:
Mtotal ≈ p × M
This relationship is a capacity estimate, not a universal performance law. It assumes concurrent operations each require approximately M bytes and ignores implementation overhead. Increasing memory can make large-scale parallel attacks more expensive, but excessive settings can create denial-of-service risk for the application.
Choosing parameters
Parameter selection must be tested on production-like hardware. A reasonable engineering process is:
select a supported algorithm, commonly Argon2id for a new application;
choose memory, time, and parallelism parameters using current guidance from the library or security standard;
benchmark registration and login under expected concurrency;
ensure the endpoint cannot be cheaply abused to consume excessive resources;
record parameters in the hash string;
periodically review and increase parameters as infrastructure changes.
There is no single universal work factor. A setting suitable for a small internal application may be inappropriate for a large public service or a low-powered mobile backend. Measure rather than copying a number without understanding its environment.
Verification and comparison
A login implementation should pass the supplied password to the password-hashing library's verification function. It should not recompute a fast hash or compare plaintext values. The library should perform a constant-time comparison where appropriate. Constant-time comparison reduces timing leakage when comparing secret-derived values, but it does not solve all timing problems in a complete request: database lookup, account existence, rate limiting, and network behavior may still differ.
A typical record may include:
algorithm = argon2id
memory = configured value
iterations = configured value
parallelism = configured value
salt = random value
hash = derived verifier
Never log passwords, reset tokens, one-time codes, or complete authorization headers. Avoid placing credentials in URLs because URLs can be stored in browser history, proxy logs, analytics systems, and referrer data.
3. Registration, Login, and Credential Lifecycle
Registration
A secure registration process should:
use TLS for the entire session;
normalize only what is semantically appropriate, such as email comparison rules, without silently altering a password;
reject passwords found in a breached-password corpus;
apply a length-oriented policy and permit password-manager-generated values;
hash the password in a controlled server-side process;
avoid returning sensitive details in error messages;
send verification messages through a secure, expiring mechanism when email verification is required.
Passwords should generally be accepted as typed, including spaces, subject to a maximum length that protects resources. Arbitrary composition rules such as “one uppercase, one symbol, and one digit” often encourage predictable substitutions. Length, uniqueness, breached-password screening, MFA, and password managers are usually more valuable.
Login
A robust login sequence is:
receive the identifier and password over TLS;
normalize the identifier according to a documented policy;
retrieve the account record through a parameterized query;
perform a password-hash verification using the stored parameters;
apply risk, throttling, and account-status checks;
issue a new session identifier after successful authentication;
record a privacy-conscious security event;
offer step-up authentication for sensitive actions.
Session identifiers must be unpredictable, transmitted securely, protected with appropriate cookie attributes, and rotated after login or privilege changes. Password authentication is only one stage in the complete account-security lifecycle.
Password changes
A password change should normally require the current password or a recently completed strong authentication step. The new password must be screened against breached-password data and hashed with current parameters. Invalidate or review existing sessions and recovery mechanisms according to the risk model. A notification should be sent through an independent channel, while avoiding disclosure of the new password.
4. Breached Passwords and Password Reuse
A breached password is a password known to have appeared in a public or private compromise. Attackers routinely test such passwords automatically. A password can be long and still unsafe if it is common, exposed, or reused.
Breached-password screening can use:
a locally maintained, privacy-preserving corpus;
a trusted service using a protocol that does not reveal the complete password;
a keyed or partially disclosed lookup design, carefully evaluated for leakage.
The application should compare a secure representation of the candidate password with the screening database before accepting it. The screening service should not receive plaintext passwords unless the organizational risk assessment explicitly justifies that design.
Screening is not a substitute for hashing. It protects against known weak choices, whereas hashing protects stored credentials if the database is disclosed. Screening also cannot identify every password that will later be exposed.
5. Online Attack Defenses
Rate limiting
Rate limiting restricts requests over time. It can be applied by account, source address, device or session signal, network range, endpoint, and organization. No single key is sufficient: IP-only controls can be bypassed through distributed infrastructure, while account-only controls can be abused to deny service to a victim.
A token-bucket model is useful conceptually. If a bucket has capacity B tokens, refills at rate r tokens per second, and each request consumes c tokens, then a request is allowed only when at least c tokens are available. The bucket can absorb short bursts up to its capacity while limiting sustained traffic. This is a control model, not a guarantee of attacker identity.
Rate limits should be graduated. For example, the system may permit normal human use, introduce increasing delays after failures, require MFA or a challenge at elevated risk, and block clearly abusive automation. A global limit protects infrastructure, while per-account and per-identifier limits protect users.
Lockout and progressive delay
Hard lockouts can create denial-of-service attacks: an attacker can repeatedly fail authentication against a target account and prevent its owner from logging in. Permanent or long lockouts are therefore often inferior to progressive delays, risk-based challenges, or temporary controls with secure recovery.
If lockout is used, define:
the failure window;
the threshold and duration;
whether failures are counted by account, device, source, or a combination;
how legitimate users recover;
how administrators detect abuse;
how the policy avoids revealing account existence.
Controls should be tested against distributed guessing and password spraying rather than only repeated attempts against one account.
Credential stuffing and password spraying
Credential stuffing uses a known username-password pair against many services. The key defenses are MFA, breached-password rejection, password-manager support, bot and automation detection, device and behavioral risk analysis, and monitoring for unusual login patterns.
Password spraying uses one or a few common passwords across many accounts to remain below per-account thresholds. Defenses include tenant-wide detection, common-password blocking, adaptive challenges, MFA, and correlation by source, autonomous system, device characteristics, and time. Security teams must consider privacy and false positives when collecting behavioral signals.
6. Account Enumeration and Error Design
Enumeration occurs when an attacker learns whether an identifier is registered. Leakage can arise from messages such as “email not found,” different response times, different status codes, password-reset behavior, or registration screens.
For public authentication and recovery endpoints, use a generic response such as: “If an account matches the supplied information, further instructions will be sent.” Keep observable behavior as similar as practical, while recognizing that perfect indistinguishability is difficult because email delivery and database operations have different timing.
Enumeration resistance must not prevent legitimate support and accessibility. Administrative tools may provide authorized, audited visibility, while public endpoints provide minimal disclosure. Logs should contain sufficient internal detail for investigation without exposing secrets to users or untrusted operators.
7. Secure Account Recovery
Recovery is often the weakest authentication path. A password that is difficult to guess is irrelevant if an attacker can reset it through an insecure email link or support process.
A secure reset flow should:
accept a reset request without confirming whether the account exists;
generate a cryptographically random, single-use, short-lived token;
store only a protected representation of the token where practical;
send the token through a channel whose security is understood;
invalidate the token after use, expiration, or replacement;
require the new password to satisfy current screening and hashing policy;
notify the account owner of the reset;
revoke or review active sessions and recovery factors based on risk.
A reset token is a bearer credential: possession may be sufficient. It must therefore be treated like a password. Do not place long-lived reset credentials in logs or expose them through referrer headers. Use HTTPS, appropriate response headers, and careful redirect behavior.
Email recovery is convenient but depends on the security of the email account. High-value accounts should use stronger recovery factors, such as previously registered security keys or verified organizational procedures. Support personnel must follow documented identity-proofing procedures and should never ask for a user's password.
8. Phishing-Resistant Authentication
Passwords can be copied by convincing users to enter them into a fraudulent page. Conventional one-time passwords improve resilience against replay but may still be phished in real time. Passkeys and WebAuthn use public-key cryptography and origin binding: the authenticator creates or uses a private key, while the service stores the public key. The private key is not sent to the server during login.
For a high-risk application, a layered strategy is appropriate:
encourage passkeys or hardware security keys;
require MFA for privileged and sensitive operations;
bind authentication to the correct origin where supported;
train users to verify unexpected requests without relying solely on awareness;
protect sessions after authentication;
use transaction confirmation for high-impact actions.
Biometrics used by a device authenticator generally unlock a local key rather than being transmitted as a server-side password. This distinction reduces some privacy and replay risks, but device compromise and account recovery remain relevant.
Figure: A conceptual architecture for password authentication, risk controls, and recovery.
The API should be the policy enforcement point, but important controls should be distributed. A database stores password verifiers and account state. A rate-limiting or risk service correlates failures and suspicious activity. A recovery service manages short-lived tokens and notifications. Security logs should be centralized, access-controlled, integrity-protected, and monitored.
Defense in depth is essential. TLS protects credentials in transit, hashing protects verifiers at rest, MFA reduces the value of stolen passwords, rate limiting reduces online guessing, and monitoring supports detection and response. None of these controls is sufficient alone.
10. Illustrative Case: University Learning Platform
Background
A fictional university learning platform has 80,000 accounts. It stores passwords using a fast SHA-256 digest and returns “user not found” when an email address is unknown. The password-reset endpoint sends a permanent link and does not invalidate previous links.
Problem
An attacker obtains a list of email addresses from the public directory. The attacker enumerates active accounts, tests passwords from earlier breaches, and requests resets for selected users. Because the reset links remain valid, a forwarded or logged link can be reused.
Analysis
The fast digest makes an offline database compromise dangerous. The explicit error enables enumeration. Per-IP rate limiting is ineffective against a distributed botnet, and permanent reset tokens create a long-lived bearer credential. The platform also lacks MFA for staff and administrators.
Approach and solution
The university migrates to Argon2id using a maintained library and stores algorithm parameters with each verifier. Existing users are upgraded after successful login, while inactive accounts are required to reset through a controlled process. New and changed passwords are checked against a privacy-preserving breached-password corpus.
The login service applies layered limits by account, identifier, source, and tenant, with progressive delays and risk-based MFA rather than indefinite hard lockouts. Public responses are generalized. Reset tokens are random, single-use, short-lived, stored in protected form, and invalidated after use. Reset requests generate consistent user-facing responses and security notifications.
Staff and administrators must use phishing-resistant MFA. Session identifiers rotate after authentication, and sensitive actions require recent authentication. Security events are correlated to detect password spraying, unusual recovery activity, and impossible travel signals, subject to privacy review.
Outcome
The design reduces the value of a database disclosure, makes large-scale guessing more expensive, limits recovery abuse, and improves detection. It does not claim to prevent every compromise: a stolen email account, infected endpoint, or hijacked session remains a material risk.
Learning points
A fast hash is not an appropriate password verifier.
Recovery and login must be secured as one authentication system.
Controls should address distributed attacks, not only repeated attempts from one IP address.
Generic public responses reduce enumeration but must be supported by useful internal monitoring.
MFA, particularly phishing-resistant MFA, changes the consequences of password theft.
11. Governance, Ethics, and Operational Limits
Account security involves personal data and can affect access to education, employment, health services, and finances. Organizations should collect only signals necessary for security, define retention periods, restrict staff access, and document automated decisions. Risk scoring can disadvantage users behind shared networks, travelers, people with disabilities, or users of privacy technologies. False positives require accessible recovery and appeal processes.
Regulatory and contractual requirements vary by jurisdiction and sector. Developers should consult applicable data-protection, breach-notification, payment, education, and cybersecurity requirements rather than assuming that one standard applies universally. Security controls should be reviewed through threat modeling, code review, dependency management, penetration testing, incident exercises, and usability testing.
Operationally, password hashing consumes CPU and memory. A poorly tuned configuration can become a denial-of-service vector. Monitor latency, error rates, queue depth, and resource consumption. Separate expensive authentication work from unrestricted anonymous traffic where possible, and use circuit-breaking or infrastructure-level controls during attacks.
Best-Practice Checklist
Store no plaintext passwords.
Use a maintained adaptive password-hashing library, preferably Argon2id for new systems where appropriate.
Generate a unique cryptographically random salt for every password.
Store algorithm parameters with each verifier.
Use breached-password screening and permit password managers.
Apply layered rate limits and monitor password spraying.
Avoid indefinite hard lockouts that attackers can weaponize.
Return enumeration-resistant public responses.
Use short-lived, single-use, protected recovery tokens.
Rotate sessions after authentication and privilege changes.
Require MFA for sensitive accounts and actions; prefer phishing-resistant methods.
Never log passwords, reset tokens, or authentication secrets.
Test security controls under realistic load and distributed attack patterns.
Chapter Summary
Secure credential management is a lifecycle discipline. Passwords should be transmitted over protected channels, transformed with a unique salt and an adaptive password-hashing algorithm, and verified through a trusted library. Adaptive cost increases the work of offline guessing, while breached-password screening reduces acceptance of credentials already known to attackers.
Online defenses require layered controls: rate limiting, progressive delays, risk-based challenges, MFA, monitoring, and careful handling of distributed credential stuffing and password spraying. Hard lockout alone can create denial of service. Generic public responses and consistent recovery behavior reduce account enumeration. Recovery tokens must be random, short-lived, single-use, and treated as bearer credentials.
Passwords cannot reliably resist phishing on their own. Passkeys and other phishing-resistant authenticators provide stronger protection, especially for administrators and high-value operations. Finally, security design must account for privacy, accessibility, operational capacity, governance, and the possibility that every individual control can fail.
Key Terms
Authentication: Verification of a claimed identity.
Authorization: Determining what an authenticated identity may access or do.
Adaptive hashing: Password hashing with configurable computational or memory cost.
Salt: A unique random value combined with a password before hashing.
Password verifier: Stored data used to test a password without storing it directly.
Argon2id: A memory-hard password-hashing algorithm suitable for many new systems.
Credential stuffing: Automated use of credentials stolen from another service.
Password spraying: Testing a small set of common passwords against many accounts.
Brute force: Systematic guessing of possible credentials.
Phishing: Deception designed to obtain secrets or induce harmful actions.
Enumeration: Discovering whether an account or resource exists.
Rate limiting: Restricting request frequency or volume.
Progressive delay: Increasing response delay after suspicious or failed attempts.
Account lockout: Temporarily restricting authentication after policy-defined failures.
MFA: Authentication using two or more independent factors.
Passkey: A public-key credential usable for phishing-resistant authentication.
Recovery token: A temporary bearer value used to regain account access.
Session fixation: An attack involving use of a session identifier established before authentication.
Password spraying: Trying common credentials broadly rather than many passwords against one account.
Threat model: A structured description of assets, adversaries, attack paths, and controls.
Review Questions
Short Answer Questions
Why is a salt stored with a password verifier rather than kept secret?
Why are fast general-purpose hashes unsuitable for password storage?
Distinguish credential stuffing from password spraying.
State two properties of a secure password-reset token.
Why can hard account lockout create a denial-of-service problem?
Long Answer Questions
Explain the complete lifecycle of a password from registration through verification, change, and recovery.
Compare Argon2id, bcrypt, scrypt, and PBKDF2 in terms of design goals and deployment considerations.
Design a layered defense against a distributed credential-stuffing campaign.
Explain how account enumeration occurs and propose controls for login, registration, and recovery endpoints.
Discuss why phishing-resistant MFA is a stronger complement to passwords than awareness training alone.
Analytical / Application Questions
A service uses a fast hash, IP-only rate limiting, and permanent reset links. Analyze the attack paths and prioritize remediation.
Design a rate-limiting policy for a university platform that must support shared campus networks without enabling password spraying.
Evaluate the privacy, accessibility, and security trade-offs of using device and behavioral risk signals in authentication decisions.
Multiple Choice Questions with Answers
Question 1
Which property most directly prevents identical passwords from producing identical stored password records?
A. A unique random salt for each password
B. A longer username
C. A generic login error
D. A session timeout
Correct Answer: A. A unique random salt for each password
Question 2
Why is a fast hash such as SHA-256 generally unsuitable as the primary password-storage function?
A. It cannot process text passwords
B. It is designed to be computationally expensive for every guess
C. Its speed enables attackers to test very large numbers of guesses
D. It requires a public key
Correct Answer: C. Its speed enables attackers to test very large numbers of guesses
Question 3
What is the main characteristic of an adaptive password-hashing function?
A. It encrypts passwords with a reversible key
B. Its work factor can be adjusted as computing capabilities change
C. It makes salts unnecessary
D. It prevents phishing
Correct Answer: B. Its work factor can be adjusted as computing capabilities change
Question 4
Which attack uses username-password pairs stolen from other websites?
A. Credential stuffing
B. Password spraying
C. Session fixation
D. Shoulder surfing
Correct Answer: A. Credential stuffing
Question 5
Which recovery-token design is most secure?
A. A permanent token based on the username
B. A predictable token containing the account ID
C. A random, short-lived, single-use token
D. A token printed in application logs
Correct Answer: C. A random, short-lived, single-use token
Question 6
Why can an indefinite hard lockout be harmful?
A. It makes password hashing impossible
B. An attacker can deliberately lock out a legitimate user
C. It prevents the use of TLS
D. It causes salts to collide
Correct Answer: B. An attacker can deliberately lock out a legitimate user
Question 7
Which response best reduces public account enumeration during password reset?
A. “That email address is not registered.”
B. “The password was incorrect.”
C. “If an account matches, further instructions will be sent.”
D. Returning the account creation date
Correct Answer: C. “If an account matches, further instructions will be sent.”
Question 8
Which control most directly addresses passwords already exposed in known breaches?
A. Breached-password screening
B. Longer session duration
C. A larger user interface
D. Disabling audit logs
Correct Answer: A. Breached-password screening
Question 9
What is a principal advantage of passkeys over passwords?
A. They are always memorized by the user
B. They use origin-bound public-key authentication that is more resistant to phishing
C. They eliminate the need for account recovery
D. They require the server to store the private key
Correct Answer: B. They use origin-bound public-key authentication that is more resistant to phishing
Question 10
If an attacker tests one common password across many accounts, which attack pattern is being used?