Secure Design and Engineering Practices for Authentication Systems

    This article provides a systematic overview of secure design and engineering practices for building login and registration systems. It covers critical areas including account data modeling, secure registration and login flows, password hashing, session management, password recovery, risk control against brute-force and batch registration attacks, frontend and backend validation, automated testing, and observability through logging and monitoring. The goal is to help engineers build authentication modules that are secure, maintainable, and scalable in production environments.

    Why Authentication Systems Need a Systematic Design Approach

    Login and registration may appear to be simple “submit username and password” features, but they actually involve multiple critical processes: identity establishment, credential protection, session maintenance, anomaly detection, permission integration, and data compliance. A poorly designed authentication system can lead to issues such as password leakage, CAPTCHA bypass, session fixation, duplicate registrations, API abuse, and unauthorized access.

    Therefore, login and registration should not be treated as single-page features, but rather designed as part of a unified identity management system. The core objectives include:

    1. Confirming the visitor’s identity: Determining whether the requester is the actual account holder.
    2. Protecting authentication credentials: Preventing sensitive data such as passwords, verification codes, and tokens from leaking.
    3. Maintaining access state: Recognizing authenticated users within a specified time frame.
    4. Limiting abnormal behavior: Reducing risks of brute-force attacks, batch registration, and automated abuse.
    5. Supporting business expansion: Providing a foundation for user profiles, permission management, single sign-on, and multi-factor authentication.

    Account Model and Data Structure Design

    The first step in building a registration feature is not creating a form, but defining a clear account model. It is recommended to separate the “user entity” from “login credentials” in the data design.

    The user entity table can store the following information:

    • Unique user identifier
    • Nickname or display name
    • Account status (e.g., active, frozen, deactivated)
    • Creation time and last update time
    • Last login time
    • Risk level or security status

    The login credential table is used to store different types of authentication information, such as:

    • Login identifier (phone number, email, etc.)
    • Password hash value
    • Credential type
    • Verification status (whether the credential has been verified)
    • Number of failed attempts
    • Last modification time
    • Credential expiration time

    This separation offers several advantages. First, a user can bind multiple login methods, such as password login, SMS verification, or enterprise identity authentication. Second, changing a password does not affect the user profile. Third, account deactivation, credential freezing, and risk control can be handled independently, reducing data coupling.

    Account identifiers must have unique constraints enforced. Note that email addresses should typically have consistent case handling, phone numbers should be formatted uniformly, and for usernames, it is necessary to explicitly define whether case sensitivity is allowed. All uniqueness checks should be enforced at the database level, not solely relying on frontend validation, otherwise concurrent registrations may result in duplicate accounts.

    Secure Implementation of the Registration Flow

    A relatively complete registration flow can be broken down into the following steps:

    1. The user submits an account, password, and CAPTCHA.
    2. The server validates field formats and lengths.
    3. The server checks whether the account already exists.
    4. The server verifies the CAPTCHA.
    5. The password is securely hashed.
    6. The user entity and login credentials are created.
    7. An audit record is written.
    8. Depending on business needs, automatic login or a re-verification step is performed.

    Passwords must never be stored in plaintext or in reversibly encrypted form. The correct approach is to use dedicated password hashing algorithms and generate a unique random salt for each account. When verifying a password, the system recomputes the hash and performs a secure comparison, rather than comparing raw strings.

    Password policies should not solely pursue complexity. Excessively complex rules often lead users to reset passwords frequently or store them in insecure places. A more reasonable policy includes:

    • Setting a reasonable minimum length.
    • Rejecting obviously weak passwords.
    • Prohibiting commonly leaked passwords from public breach databases.
    • Supporting random passwords generated by password managers.
    • Providing a secure recovery and change process.
    • Applying rate limiting and risk escalation for consecutive failures.

    Registration APIs also need protection against batch calls. CAPTCHA, device fingerprinting, request frequency limits, and behavioral analysis can be used in combination, but all security responsibility should not be delegated to CAPTCHA alone. The CAPTCHA itself should also have an expiration time, a maximum number of attempts, and a usage limit, and it should be invalidated immediately after successful verification to prevent reuse.

    Login Flow and Session Management

    The login flow typically consists of four stages: account lookup, password verification, risk assessment, and session creation.

    The server should first normalize the input and then look up the account. For non-existent accounts and incorrect passwords, the returned message should be kept as consistent as possible, to prevent attackers from enumerating valid accounts through error messages. For example, it is not advisable to respond with “account not found” versus “incorrect password”; instead, a generic authentication failure message should be returned.

    Password verification needs to avoid obvious timing differences. For non-existent accounts, an equivalent computation should be performed to prevent attackers from inferring account existence through response time.

    After successful authentication, the system needs to create a session. Common approaches include server-side sessions and token-based mechanisms:

    • Server-side sessions: The client only holds a random session identifier, while the actual state is stored on the server or in a cache. This approach facilitates proactive logout and risk control.
    • Token-based mechanisms: The client carries an access token when calling APIs. This is suitable for microservice architectures, but token expiration, refresh, revocation, and leakage issues must be addressed.

    Regardless of the chosen approach, the following principles should be followed:

    • Use encrypted transport (TLS) throughout the entire process.
    • Session identifiers must be cryptographically strong random values.
    • The session identifier should be regenerated after successful login to prevent session fixation attacks.
    • Set reasonable idle timeout and absolute expiration time.
    • Invalidate sessions immediately upon logout.
    • In browser contexts, set appropriate security flags on cookies (such as HttpOnly and Secure) to reduce the risk of script theft and cross-site request forgery (CSRF).
    • Never expose access tokens in URLs, logs, or error messages.

    If the system uses refresh tokens, rotation should be implemented. Each refresh should invalidate the previous token and record the token family relationship. If the same refresh token is detected as being reused, all associated sessions should be revoked, and the user should be prompted to re-authenticate.

    Password Recovery and Protection of Sensitive Operations

    Password recovery is a high-risk flow, and its security level should be no lower than that of normal login. The system must not lower identity verification requirements simply because a user has forgotten their password.

    A common practice is to send a one-time link or verification code to the user’s verified contact method (email or phone). This credential needs to have the following characteristics:

    • Randomly generated with sufficient length.
    • Valid for single use only.
    • Set to a short expiration time.
    • Bound to a specific user and operation.
    • Becomes invalid after reaching a maximum number of verification failures.
    • Full credentials are not recorded in logs.

    After a password reset is completed, it is recommended to revoke the user’s other existing login sessions, especially when abnormal recovery, device changes, or high-risk location changes are detected. For sensitive operations such as changing passwords, binding contact methods, or disabling multi-factor authentication, users should be required to re-enter their password or complete a second verification step.

    Risk Control and Abnormal Behavior Detection

    Authentication systems typically face three categories of attacks:

    1. Brute-Force Attacks

    Attackers repeatedly attempt different password combinations. Protective measures include:

    • Rate limiting by account, device, and network address.
    • Increasing wait times after consecutive failures.
    • Triggering image or behavioral CAPTCHAs.
    • Temporarily banning abnormal sources.
    • Monitoring failure rates and characteristics of distributed attack patterns.

    Permanent account lockout is not recommended, because attackers could exploit this mechanism to maliciously lock out other users’ accounts. A more reasonable approach is progressive delay combined with risk-based verification.

    2. Batch Registration

    Attackers use automated scripts to create a large number of accounts, possibly for activities such as inflating metrics, abusing promotional benefits, or attacking other business services. Measures can include registration frequency control, device association analysis, contact method verification, IP reputation checks, and behavioral trajectory detection.

    3. Session Hijacking

    Once a token is leaked, an attacker can bypass password authentication entirely. Therefore, it is necessary to shorten session validity under high-risk scenarios, monitor device and location changes, and require re-authentication for sensitive operations. Systems should also avoid writing tokens into normal business logs, monitoring events, or client-side error reports.

    Frontend/Backend Validation and Error Handling

    Frontend validation exists to improve the user experience, such as checking whether fields are empty or whether password length meets requirements. However, frontend validation must not be relied upon for security. All rules must be re-enforced on the server side.

    Error responses should achieve the following:

    • Do not leak database structure information.
    • Do not return stack traces.
    • Do not reveal whether an account exists.
    • Do not include passwords, verification codes, or tokens.
    • Use unified error codes that the frontend can handle.
    • Write detailed reason logs to a controlled audit log rather than returning them to the user.

    For API exceptions, the system should distinguish between client input errors, authentication failures, insufficient permissions, rate limit triggers, and server failures. Clear error classification facilitates monitoring and troubleshooting, while also preventing the frontend from indiscriminately displaying “incorrect password” for all errors.

    Automated Testing and Quality Assurance

    Login and registration modules are well-suited for layered testing approaches. Unit tests verify details such as password policy, verification code expiration, token validity, and failure counters. API tests verify the complete authentication flow. Integration tests check the collaboration between database, cache, and messaging components. Security tests validate rate limiting, CSRF protection, session fixation prevention, and unauthorized access control.

    At a minimum, the following scenarios should be covered:

    • Normal registration.
    • Registration with a duplicate account.
    • Passwords that are too short or are weak passwords.
    • Expired, incorrect, and reused verification codes.
    • Login with a correct password.
    • Consecutive attempts with incorrect passwords.
    • Login behavior when an account is frozen.
    • Re-accessing after logout.
    • Whether old sessions become invalid after a password change.
    • Whether a password recovery credential can only be used once.
    • Multi-device login and session revocation.
    • Unique constraint enforcement during concurrent registration.

    Automated tests should not only verify that “the API returns success.” They should also check data states. For example, after successful registration, verify that only one user record was created, that the password is an irreversible hash, that failed logins generate audit events, and that revoked session tokens truly cannot access protected resources.

    Logging, Monitoring, and Auditing

    Authentication systems must be observable. It is recommended to record the following events:

    • Successful or failed registration.
    • Successful or failed login.
    • Password changes and resets.
    • Contact method binding or change.
    • Multi-factor authentication enabling or disabling.
    • Session creation, refresh, and revocation.
    • Risk interception and account freezing.

    Logs must not contain plaintext passwords, full verification codes, access tokens, or other sensitive information that could directly compromise an account. Masked account identifiers, device summaries, request sources, timestamps, results, and risk levels should be recorded instead.

    Key monitoring metrics include login success rate, failure rate, verification code error rate, password reset volume, abnormal device count, API response time, and rate limit trigger count. When a sudden increase in failure rates, a single source accessing a large number of accounts, or an abnormal surge in registration volume is detected within a time window, alerts should be triggered, and emergency response strategies should be activated.

    Implementation Recommendations

    When building an authentication system, it is recommended to proceed in the following order:

    1. Define the account model and identity boundaries.
    2. Implement foundational capabilities such as password hashing, verification codes, and session management.
    3. Establish unified error handling and auditing mechanisms.
    4. Add rate limiting, device fingerprinting, and anomaly detection.
    5. Implement password recovery and second-step verification for sensitive operations.
    6. Use automated tests to cover core and exceptional flows.
    7. Continuously adjust security policies based on monitoring data.

    A reliable authentication system does not achieve security through a single feature. Instead, it builds a defense line through data constraints, password protection, session management, risk control, log auditing, and continuous testing. Only by striking a balance among security, user experience, and maintainability can the login and registration module truly serve as a stable foundation for the broader business system.