Content Platform Identity System Design: From Anonymous Browsing to Login Authentication
Designing an identity system for a content platform is far more than adding a login popup. This article walks through a practical, production-ready design that covers anonymous browsing and login gating, account models, tokens and sessions, permission matrices, entitlement checks, playback URL signing, multi-device sync, danmaku (bullet comments), moderation, and degradation strategies. You will learn how to centralize identity decisions while decoupling business logic, how to convert guests into registered users without hurting browsing, how to issue and revoke sessions safely, how to enforce tiered access on the server, and how to keep watch progress consistent across devices. The article closes with a phased rollout plan and five core principles for building identity infrastructure that can support long-term growth.
1. Background: A Login Wall Should Not Be Just a Button
When users browse videos, comics, or article-and-image content, the common flow is: unauthenticated users can look around first; when they tap high-definition playback, post a comment, favorite an item, or sync their records, the page shows a login prompt; after logging in they return and finish the original action; meanwhile, entry points like messages, activity feeds, and favorites also indicate that login is required.
From a product perspective, this is just buttons and popups. From an engineering perspective, it maps to an identity infrastructure that spans the entire site: anonymous identity, registration and login, tokens and sessions, permission checks, entitlement checks, multi-device sync, and interaction risk control. If any link is designed crudely, the problems surface all at once as traffic grows:
- Low registration conversion: blocking guests from browsing turns away visitors who only want a quick look.
- Missing permission checks: quality and comment permissions judged only on the frontend can be bypassed by calling the API directly.
- Chaotic session management: long-lived tokens that do not expire after logout, or devices kicking each other offline, hurt both security and experience.
- Inconsistent data state: phone, tablet, and web each store a separate progress copy that overwrites the others.
- Out-of-control interaction: danmaku and comments without rate limiting and moderation get flooded by spam.
So login should not be treated as a single page but as a “capability layer”: guests can try things out, only key actions prompt login, and every security boundary is enforced on the server.
2. Overall Architecture: Making Login a Capability Layer
A sound identity system can be designed across four layers — “access, identity, business, support”:
- Access layer: web, mobile, clients, and open APIs all pass through an access gateway that terminates protocols, applies basic rate limiting, and validates request parameters.
- Identity layer: handles registration, login, token issuance and validation, session management, device binding, multi-device login control, and permission decisions. It is the single trusted source of identity.
- Business layer: content services, playback services, entitlement services, watch-progress services, danmaku and comment services, message and notification services, and more. These only consume the conclusions produced by the identity layer.
- Support layer: common capabilities such as distributed cache, message queues, object storage, and logging, monitoring, and alerting.
There is only one core principle: centralize identity decisions, decouple business logic. If login and permission rules are scattered across business modules, every rule change requires editing and regression-testing each one, and things quickly spiral out of control.
2.1 Defining Capability Boundaries with an “Action–Identity–Entitlement” Matrix
Before writing code, first abstract the product rules into a capability matrix that serves as a contract for both frontend and backend:
| User action | Guest | Logged-in user | Paying member |
|---|---|---|---|
| Browse lists, details, and basic-quality playback | Allowed | Allowed | Allowed |
| HD playback, ad-free and other value-added features | Not allowed | Not allowed | Allowed |
| Post danmaku, write comments, favorite | Not allowed, prompt login | Allowed | Allowed |
| Sync watch records across devices | Not allowed | Allowed | Allowed |
| Download, bulk favorite, and other extended features | Not allowed | Not allowed | By membership tier |
Each row in the matrix should map to an enumerable action identifier, such as view_detail, play_sd, play_hd, post_comment, sync_progress, and download. The code examples below only demonstrate the decision logic; in a real system these should be delivered by a configuration center or a permission table, avoiding hardcoded rules scattered across business code.
2.2 Guests Have Identity Too: Anonymous Tokens and Login Conversion
“Can’t watch without logging in” raises the bounce rate. A better approach is to assign guests an anonymous device token so lightweight features like personalized recommendations, temporary favorites, and local watch history work before login. After a successful login, the system migrates and merges the anonymous data into the real account, so the user does not feel any break.
The timing of the login prompt also needs design:
- Immediate trigger: show it the moment the user taps a high-value action like HD playback, posting a comment, or syncing records, when intent is clearest.
- Deferred trigger: invite login after the user has browsed several items or generated some interaction, causing less interruption.
In practice, use “immediate as primary, deferred as secondary,” and use instrumentation to continuously compare registration conversion and next-day retention across strategies.
3. Login and Registration: From Anonymous Identity to Trusted Session
3.1 A Unified User Identifier Model
A common mistake is using a phone number or third-party account identifier directly as the user primary key. Once a user changes their phone number, unbinds a third-party account, or merges duplicate accounts, large amounts of historical data must be migrated.
A more robust approach is to establish an internal user identifier and keep “identity decoupled from login credentials”:
- Internal user ID: globally unique within the system and never changes; it serves as the join key for business data.
- Credential table: records login methods such as phone, email, and third-party authorization identifiers, associated many-to-one with the user ID.
- Account status: active, pending activation, frozen, deactivated, and so on.
-- Illustrative, simplified schemaCREATE TABLE app_user (user_id BIGINT PRIMARY KEY,status SMALLINT NOT NULL,pass_hash VARBINARY,created_at TIMESTAMP NOT NULL);CREATE TABLE user_credential (cred_id BIGINT PRIMARY KEY,user_id BIGINT NOT NULL,cred_type SMALLINT NOT NULL,cred_key_hash VARBINARY NOT NULL,verified BOOLEAN NOT NULL,UNIQUE (cred_type, cred_key_hash));
For sensitive information such as phone numbers, store an irreversible hash for login matching, and separately keep an encrypted form for display. The two serve different purposes and should not be mixed.
3.2 Registration and Login: One Entry, Two Branches
From the user’s perspective, registration and login are often the same thing: enter a phone number, get a verification code, pass verification, and identity is established. Internally the system can handle it like this:
- Credential verification: look up whether a user already exists by credential type and hash value.
- Exists: issue a token directly and complete login.
- Does not exist: if auto-registration is allowed, create the user and credential; if explicit registration is required, enter a follow-up flow to set a password or nickname.
- Account binding: when a logged-in user binds a new phone number, establish the binding relationship after the credential passes, rather than creating a new account.
The key point is that identity confirmation and account creation are two independent steps. After the credential is verified, first determine “who this is,” then decide “whether an account needs to be opened.” The registration flow can be adjusted flexibly without affecting login logic.
3.3 Verification Codes: Issuance and Validation Under High Concurrency
Verification codes are the most easily overlooked link in phone-number login:
- The server generates the code and sets its time-to-live.
- Apply a send-frequency limit to the same phone number, e.g., only one send per minute.
- Set a daily send cap per device and per network segment.
- A code is single-use and is invalidated immediately after a successful verification.
- Use isolated code channels per scenario, such as registration, login, password reset, and re-binding.
- Failed verifications also count toward the failure tally; once a threshold is reached, lock that phone number for a period to prevent brute-force enumeration.
- For financial or sensitive operations, layer on device fingerprinting and risk scoring; require a second verification when risk is high.
# Illustrative pseudocode: code issuance and validationdef send_code(phone, scene):if not limiter.try_acquire(f"code:{scene}:{phone}", period=60, limit=1):raise RateLimitedcode = random_six_digits()code_store.setex(f"code:{scene}:{phone}", ttl=300, value=code)sms_gateway.send(phone, render_template(code))return None # never return the code to the client under any circumstancedef verify_code(phone, scene, code, attempts):key = f"code:{scene}:{phone}"if attempts >= MAX_ATTEMPTS:raise Lockedif code_store.compare_and_delete(key, code):fail_counter.reset(key)return True# failures also count; lock once the threshold is hit to prevent brute-force enumerationfail_counter.incr(key)if fail_counter.get(key) >= MAX_ATTEMPTS:code_store.delete(key)raise Lockedreturn False
3.4 Password Login: Storage, Transmission, and Protection
Password login should still be kept for compatibility with users who prefer it, but the security requirements are higher:
- Storage: passwords must not be stored in plaintext or reversible encryption; use a salted slow hash such as an Argon2-family algorithm.
- Transmission: enforce encrypted transmission site-wide; password fields must not enter access logs, crash logs, or frontend telemetry.
- Credential-stuffing defense: rate-limit the login endpoint across account, device, and IP dimensions; after consecutive failures reach a threshold, introduce a graphical or behavioral challenge and send an unusual-login alert.
- Anomaly detection: for scenarios like logins from a new location or new device, confirm the actor’s identity via notification or second-factor verification.
3.5 Sessions and Tokens: The Trade-off Between Stateless and Stateful
After identity is confirmed, the system needs subsequent requests to “carry identity.” Common options include self-contained tokens and centralized sessions. The former can be verified locally by signature, which suits multi-service deployments, but immediate revocation is hard; the latter allows immediate invalidation by deleting the session, but every request must query the session store, and that store may become a single point of failure.
In engineering, a hybrid model is common:
- Dual-token structure: the access token is a self-contained token with a short lifetime; the refresh token is a long-lived credential the server can track.
- Immediate revocation: maintain a token version number in the user record and embed it in the access token. On logout, password change, or risk-control action, increment the version; old tokens are invalidated because the version no longer matches.
- Refresh strategy: when the access token expires, exchange the refresh token for a new one; use one-time rotation for refresh tokens; if an old refresh token is used again, treat it as leaked, immediately revoke that device’s session, and raise an alert.
- Storage location: on web, prefer an
HttpOnly + Securecookie; on mobile, use the OS secure storage for the refresh token, keeping only the access token in memory.
# Illustrative pseudocode: token issuance, validation, and revocationdef issue_token(user_id, device_id):session_id = new_id()payload = {"sub": user_id,"sid": session_id,"ver": user_store.token_version(user_id),"iat": now(),"exp": now() + ACCESS_TOKEN_TTL,"aud": "content_api",}access = sign(payload, signing_key)refresh = opaque_random_token()session_store.save(session_id, user_id, device_id,refresh_hash=hash(refresh), expire=REFRESH_TTL)user_session_index.add(user_id, session_id)return access, refreshdef verify_token(token):try:payload = verify_signature_and_expiry(token)except TokenError:return Noneif payload["ver"] != user_store.token_version(payload["sub"]):return Noneif session_store.alive(payload["sid"]):return payloadreturn Nonedef revoke(user_id, session_id=None, all_devices=False):if all_devices:user_store.increment_token_version(user_id)target_sessions = user_session_index.list(user_id)elif session_id:target_sessions = [session_id]else:target_sessions = user_session_index.list(user_id)for sid in target_sessions:session_store.delete(sid)user_session_index.remove(user_id, sid)
Here, rather than relying on wildcard deletion like user:{user_id}:*, we enumerate the sessions to revoke through the user session index. The signing_key should be managed by a dedicated key-management service and support periodic rotation. If the session store is briefly unavailable, you can temporarily validate only the token signature, expiry, and token version, pausing the session_store.alive query and performing compensating checks after recovery.
3.6 Multi-Device Login Strategy
“Log in once, sync everywhere” is the experience goal, but the number of concurrent logins for one account must have an upper bound; otherwise, leaked credentials could be used in unlimited concurrency.
Common strategies:
- Mutually exclusive login: allow only a limited number of active devices per account; when a new device logs in, evict the earliest or longest-idle session.
- Parallel login: allow phone, tablet, and web online at the same time, but set a cap and provide “device management.”
Either way, the system should:
- Produce an auditable device-session record on each login.
- Require re-authentication by default for sensitive operations like password change or phone re-binding, or revoke all sessions.
- After the push channel delivers a logout command, the client should clear its local token and redirect to the login page, rather than relying solely on natural token expiry.
4. Auth Middleware: Seamlessly Bridging Login Prompts
4.1 Unified Identity Context and Decision Logic
All requests first pass through the identity layer to be parsed into a unified identity object, then decide whether to allow the action based on the matrix.
# Illustrative pseudocode: site-wide auth middlewareANONYMOUS = 0LOGGED_IN = 1MEMBER = 2ACTION_LEVEL = {"view_detail": ANONYMOUS,"play_sd": ANONYMOUS,"play_hd": MEMBER,"post_comment": LOGGED_IN,"sync_progress": LOGGED_IN,"download": MEMBER,}def authenticate(request):token = bearer_token(request.headers)payload = verify_token(token) if token else Noneif payload:user_id = payload["sub"]level = MEMBER if membership_service.is_member(user_id) else LOGGED_INreturn Identity(level=level, user_id=user_id,session_id=payload["sid"],device_id=request.device_id,anonymous=False)anon = resolve_anonymous_token(request.cookies) or issue_anonymous_token()return Identity(level=ANONYMOUS, user_id=anon.id,session_id=None, device_id=request.device_id,anonymous=True)def authorize(identity, action):required = ACTION_LEVEL[action]if identity.level < required:if identity.anonymous and action in CONVERTIBLE_ACTIONS:raise NeedLogin(action=action, return_to=current_url())raise Forbidden
This logic has two key details:
- Distinguish “login required” from “no permission.” A guest tapping comment should be prompted to log in; a regular user tapping member-only download should be told they lack permission. The client handles these differently.
- Membership is not inferred from “is logged in.” The identity level comes from the entitlement service and is then compared against the action matrix, avoiding the “logged in means all permissions” fallacy.
4.2 A Smooth Transition Between Anonymous and Logged-In States
To remove the sense of interruption, connect three layers:
- API layer: the server returns a structured “login required” response such as
NEED_LOGIN, along with the action identifier and return address, instead of a direct redirect. - Client layer: unsubmitted content, such as a half-written comment, is first saved as a local draft, then restored after successful login with focus reset.
- Data layer: favorites and watch records generated during the anonymous phase are first attached to the anonymous identifier, then batch-migrated to the real account with deduplication and merging after login.
# Illustrative pseudocode: migrating anonymous data after successful logindef on_login_success(user_id, anon_id):migrate_favorites(anon_id, user_id, conflict="keep_existing")merge_watch_history(anon_id, user_id, strategy="latest_wins")revoke_anonymous(anon_id)issue_token(user_id, current_device_id())
4.3 Unified Handling of Identity Responses on the Client
The network layer of multi-device clients should handle identity-related responses uniformly, rather than having each business module write its own. It is recommended to use uppercase constants for error codes and combine them with HTTP status codes to express the broad category.
| Response code | Suggested HTTP | Meaning | Client behavior |
|---|---|---|---|
AUTH_TOKEN_EXPIRED |
401 | Access token expired | Silently refresh the token, then replay the original request |
NEED_LOGIN |
401 | Current user is a guest | Show a login overlay, then replay the original request on success |
SESSION_REVOKED |
403 | Session was revoked | Clear the local token, redirect to login, and show the reason |
FORBIDDEN |
403 | Logged in but no permission | Show entitlement guidance, do not redirect to login |
“Silent refresh + replay” is especially important: when multiple requests expire simultaneously, only one refresh request is allowed to fire while the others wait for its result; when the refresh token is invalid, do not silently retry — switch to an explicit login.
4.4 Observability of the Login Funnel
Optimizing the login experience requires metrics. It is recommended to build a funnel from touchpoint to success:
- Login prompt reached: counted by scenario, such as HD playback, posting a comment, and syncing records.
- Verification request sent: code delivery success rate, password check failure rate.
- Identity confirmed: distinguishing new registrations from returning-user logins.
- Session issued successfully.
- Target action completed after login, e.g., whether a comment was actually submitted.
A drop in code delivery success usually points to an SMS-channel or rate-limiting problem; a low target-action completion rate after session issuance indicates a problem with the login overlay interaction or token refresh.
5. Tiered Access and Entitlement Checks
5.1 Hiding Buttons on the Frontend Is Only UX; Server-Side Checks Are the Security Boundary
Hiding or graying out buttons by identity level on the frontend is a UX improvement, not a security boundary. All rules — quality levels, downloads, comment frequency, danmaku count limits — must be independently verified on the server.
Take HD playback as an example:
- Frontend-only check: an attacker can call the API directly with an HD parameter and bypass it easily.
- Backend-only check: guests see only an error after tapping, a disjointed experience.
- Frontend–backend coordination: the frontend prompts based on the capability matrix, while the backend is the final arbiter.
5.2 Representing and Checking Entitlements
Entitlement checks should not be equated with comparing membership tiers. A tier is only an abstract level; capabilities are what the business actually cares about.
# Illustrative pseudocode: capability-set-based entitlement checkCAPTIONS = {"guest": {"play_sd"},"user": {"play_sd", "comment", "sync", "danmaku"},"member": {"play_sd", "comment", "sync", "danmaku", "play_hd", "download"},}def has_capability(user, cap):if user.anonymous:level = "guest"else:level = membership_service.level_of(user.id)return cap in CAPTIONS[level]
If you later introduce entitlement forms like pay-per-use or time-limited trials, you only need to extend the capability sources in the entitlement service; the calling convention on the business side stays unchanged.
5.3 Entitlement Caching and Real-Time Invalidation
Membership status is read frequently; querying the database every time is unnecessary and easily creates hotspots. You can:
- Cache the entitlement decision result with a short TTL.
- Increment the entitlement version number when a user’s level changes and actively delete the corresponding cache.
- Broadcast entitlement-change events via a message queue so each node invalidates its local cache.
- Allow brief degraded reads when the cache is unavailable, but do not directly grant paid capabilities; it is better to refuse temporarily than to over-authorize.
5.4 Playback URL Signing and Anti-Leech
If a playback URL is publicly accessible, anyone who obtains the URL can bypass the platform. So issue time-limited playback URLs on demand:
- On a playback request, the server completes identity resolution and entitlement checks.
- It generates a one-time URL based on permissions, including an expiry and a signature.
- The URL is usable within its validity window and must be re-fetched after expiry, and it is bound to user and device information.
- The object storage or distribution layer verifies the signature and rejects expired, tampered, or unsigned requests.
# Illustrative pseudocode: signing playback URLs by identity and entitlementdef playback_url(user, video_id, requested_quality):quality = negotiate_quality(user, video_id, requested_quality)url = cdn_signer.sign(path=f"/vod/{video_id}/{quality}/index.m3u8",expire=now() + PLAYBACK_URL_TTL,extra={"uid": user.id, "dev": user.device_id},)return url, quality
Here m3u8 is just an illustrative playlist filename; the actual format depends on the distribution scheme.
6. Multi-Device Sync: Consistency Design for Watch Records
The value of multi-device sync is only realized when the data is truly consistent. Sync problems are not “how to transmit data” but “which side is authoritative, when to overwrite, and how to merge.”
6.1 The Sync Model
- The server is the authoritative source; client-side local records serve only as offline temporary cache.
- Incremental reporting: the client reports progress on playback stop, on backgrounding, and via timed heartbeats, rather than streaming frame by frame.
- Idempotent writes: each report carries a request identifier, and the server accepts only a newer server version, so duplicate reports have no side effects.
- Server-version priority: the server receive time or a monotonic version number is authoritative, while the client timestamp only assists ordering, preventing client-clock tampering from causing wrong overwrites.
# Illustrative pseudocode: reporting watch progressdef report_progress(user_id, item_id, position_ms, client_ts, request_id):key = f"progress:{user_id}:{item_id}"if seen(request_id):return query_existing(request_id) # idempotent: return the existing result for duplicatesserver_version = server_clock.next_monotonic() # authoritative server versionprev = cache.get(key)if prev and server_version <= prev["server_version"]:return {"accepted": False, "reason": "stale"}cache.set(key, {"pos": position_ms,"server_version": server_version,"client_ts": client_ts,})queue.publish("progress.changed", {"user_id": user_id,"item_id": item_id,"position_ms": position_ms,"server_version": server_version,"client_ts": client_ts,})return {"accepted": True}
-- Illustrative persistence schemaCREATE TABLE watch_progress (user_id BIGINT NOT NULL,item_id BIGINT NOT NULL,position_ms BIGINT NOT NULL,duration_ms BIGINT NOT NULL,server_version BIGINT NOT NULL, -- authoritative monotonic server versionclient_ts BIGINT NOT NULL, -- client time, ordering aid onlyupdated_at TIMESTAMP NOT NULL,PRIMARY KEY (user_id, item_id));INSERT INTO watch_progress(user_id, item_id, position_ms, duration_ms, server_version, client_ts, updated_at)VALUES(?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)ON DUPLICATE KEY UPDATEposition_ms = IF(VALUES(server_version) > server_version, VALUES(position_ms), position_ms),duration_ms = IF(VALUES(server_version) > server_version, VALUES(duration_ms), duration_ms),server_version = GREATEST(server_version, VALUES(server_version)),client_ts = VALUES(client_ts),updated_at = CURRENT_TIMESTAMP;
6.2 Key Details
- Time basis: server time is authoritative; the client clock only assists ordering.
- Resume playback: when progress is near the end, the next playback starts from the beginning and marks the history record as watched.
- Switching quality: progress can carry over when duration is unchanged; when different versions have significantly different durations, convert by percentage.
- Offline scenarios: the client first writes to a local queue and batch-uploads after the network recovers; the server’s idempotency ensures re-uploads do not overwrite newer progress.
- Concurrent overwrite: when two devices watch the same content at once, the last server version to produce an interaction wins. After receiving a progress-change notification from another device, a client silently updates only when paused; while playing, it only shows a hint that “another device has updated progress.”
6.3 Bulk Fetch and Incremental Sync
With many devices and much content, querying progress item by item amplifies database pressure. You can:
- Maintain a user-level sync cursor on the server, incremented on every progress change.
- Have the client request the change list with its local cursor, and the server returns only records after that cursor.
- When the cursor falls too far behind, return a full snapshot and have the client rebuild local state.
This “snapshot + increment” model also applies to syncing personalized data like favorites and follows.
7. Danmaku and Comments: A Scalable Design for Interaction
7.1 Danmaku: Write-Seldom, Read-Mostly, Strongly Real-Time
Danmaku usually involves small individual records, many items per request, and high client rendering frequency. The main challenges are high-concurrency reads and batch delivery:
- Store by “content identifier + timeline bucketing.”
- The client batch-fetches danmaku within a window along the timeline cursor.
- Cache danmaku for hot content.
- When danmaku is too dense at the same timestamp, the client randomly samples for rendering to avoid flooding.
# Illustrative pseudocode: fetching danmaku by timeline windowdef list_danmaku(item_id, cursor_ms, window_ms=2000):key = f"danmaku:{item_id}"data = cache.get(key) or load_and_cache(item_id)return [d for d in data if cursor_ms < d.ts <= cursor_ms + window_ms]
7.2 The Send Pipeline for Danmaku and Comments
Sending interactions is likewise governed by the identity system: guests trigger a login prompt, and logged-in users enter the send pipeline after passing entitlement checks.
# Illustrative pseudocode: unified interaction validationdef submit_interaction(user, action, content, request_id):if user.anonymous:raise NeedLogin(action=action)assert_capability(user, "comment")if seen(request_id):return query_existing(request_id) # idempotentcheck_frequency(user.id, action) # rate controlif content_risk.hit(content):return hold_for_review(request_id) # send to manual or machine-review queueresult = store.save(user.id, action, sanitize(content))counters.incr(f"interact:{action}", tags={"result": "ok"})return result
- Idempotency: the client generates a unique request identifier for each submission, so a network-timeout retry will not publish duplicates.
- Rate control: limit the same user’s send frequency for the same content, the daily total, and repeated identical content.
- Content sanitization: escape or filter rich-text tags to prevent stored cross-site scripting, and limit length and character types.
7.3 Interaction Risk Control: Post-Then-Review vs. Review-Then-Post
Comment quality determines the community atmosphere, requiring a trade-off between timeliness and compliance:
- Machine pre-screening: low-risk content is published directly; suspicious content enters a pending state, visible only to its author, and goes into a manual review queue.
- Behavioral risk control: identify bulk spam using registration age, violation history, and device/network-segment clustering.
- User tools: provide delete, report, and block capabilities, and sample-review reported content.
- Graduated strictness: new and low-activity accounts can be held to stricter interaction rules, loosened gradually as trust accumulates.
Danmaku is more real-time, so it is usually published directly after machine pre-screening; when high-risk rules are hit, it is blocked or released with a delay.
7.4 The Read/Write Model for Interaction Data
Comments are typical read-mostly data that also needs ordering:
- Store comment bodies in a relational database to guarantee transactions and query capability.
- Put high-frequency counters like view counts and likes in cache, persisted asynchronously.
- Support sorting by heat and by time; heat is determined jointly by a time-decay factor and interaction volume, avoiding old comments being pinned forever.
- Use “sort value + unique identifier” cursor pagination for lists, avoiding the performance and consistency issues of deep pagination.
8. Security and Compliance: The Bottom-Line Checklist for an Identity System
| Risk | Typical manifestation | Countermeasure |
|---|---|---|
| Eavesdropping in transit | Tokens or passwords intercepted on the network | Enforce encrypted transmission site-wide |
| Cross-site scripting | Scripts in comments or nicknames executing in other users’ browsers | Input filtering, output escaping, Content-Security-Policy headers |
| Cross-site request forgery | A logged-in user’s identity abused to launch write operations | Set SameSite on cookies, verify origin, use one-time tokens for critical operations |
| Session fixation | Attacker presets a session identifier and lures the victim into logging in | Re-issue the session identifier after successful login |
| Brute-force enumeration | Batch attempts on phone numbers, passwords, or codes | Multi-dimensional rate limiting, failure lockout, behavioral challenges, anomaly alerts |
| Unauthorized access | Modifying parameters to access others’ data | Perform ownership checks on every resource access; never trust the client-supplied user identifier |
| Credential leakage | Tokens or passwords entering logs and telemetry | Log masking; passwords and tokens never written to disk |
| Replay attack | Intercepted legitimate requests resubmitted repeatedly | Timestamp validity, request nonces, idempotent write operations |
| Account takeover | The phone re-binding flow being exploited | Two-factor verification; revoke all old sessions on success and notify the user |
On compliance, also note:
- Data minimization: collect only information required by the business during registration.
- Masked display: phone numbers and emails shown masked by default.
- Deactivation mechanism: provide a deactivation entry; after deactivation, delete or anonymize personal data within a stated timeframe.
- Login protection: provide unusual-login alerts and a device-management entry.
9. Observability, Capacity, and Degradation
The identity system is the entry point for site-wide traffic; its own failures amplify into site-wide failures, so it must be designed for both capacity and resilience in advance.
9.1 Key Metrics
- Success rate: token validation failure rate, refresh success rate, login success rate, split by new and returning users.
- Latency: auth middleware P99 latency, entitlement query latency, overall login-endpoint latency.
- Business funnel: conversion rate from triggering login to completing the target action.
- Security risk: number of logins from new locations, high-frequency failed-login alerts, risk-control interception volume.
- Capacity: cache hit rate, session-store read/write volume, message queue backlog.
Target values should be set based on business scale and load-test results, avoiding blindly copying others’ empirical numbers.
9.2 Capacity and Hotspots
- Stateless auth: auth logic does not depend on local state and can scale horizontally; session and entitlement data live in a distributed cache.
- Hotspot isolation: viral content amplifies danmaku reads and comment writes, so rate-limit per content dimension.
- Peak shaving: non-real-time writes like progress sync and like counts are persisted asynchronously through a message queue.
- Read/write separation: read requests go to read replicas and write requests go to the primary, tolerating second-level replication lag.
9.3 Failure Degradation
| Failure scenario | Degradation strategy |
|---|---|
| Entitlement service briefly unavailable | Allow basic capabilities, refuse paid capabilities, and prompt to retry later |
| Session store unavailable | Within the access token’s validity, validate only the signature, expiry, and token version; pause the session_store.alive query and run compensating checks after recovery to avoid mass logouts or missed revocations |
| Danmaku service unavailable | Client renders locally or pauses fetching; server pauses delivery |
| Risk-control service unavailable | Comments switch to a conservative pending-review strategy; danmaku is filtered by a preset word list |
| Progress sync unavailable | Client saves locally and re-uploads after the network recovers |
Degradation strategies must be preconfigured and drilled regularly. “Allow by default” opens an over-authorization gap, while “deny by default” may make the whole site unavailable. The right approach is to distinguish basic capabilities from paid capabilities and set separate fallback plans for each.
10. Rollout Roadmap and Summary
Building an identity system does not have to happen all at once; it can proceed in three phases:
- Phase one: lay the foundation. Establish the unified user-identifier and credential model; implement phone-number verification-code login, the dual-token mechanism, and site-wide auth middleware; wire up login-funnel instrumentation.
- Phase two: fill in the experience. Introduce anonymous identity and post-login data migration; implement multi-device login control and device management; ship watch-progress sync and the entitlement capability matrix.
- Phase three: strengthen governance. Improve danmaku and comment risk control, review, and the reporting loop; build playback URL signing and anti-leech; establish capacity load-testing, failure drills, and full-link alerting.
Content platform identity system design can be condensed into five principles:
- Decouple identity from credentials: link business data via the internal user identifier.
- Centralize auth, decouple business: unified middleware and a capability matrix replace scattered checks.
- Let guests try, prompt only at key actions: use anonymous identity to drive conversion, not a login wall.
- The backend is the only security boundary: frontend control handles UX, but entitlement and ownership checks must happen on the server.
- Authoritative sync on the server, risk control as the foundation for interaction: idempotency and conflict rules determine the multi-device experience, while review and rate control determine community quality.
Whether it is a cloud-based content application or a self-hosted content platform, upgrading login from “a popup” to “a system” is fundamental groundwork for supporting long-term business growth. Once the identity layer is solid, entitlements, sync, and interaction have a reliable foundation; otherwise, the more features you layer on later, the higher the cost to fix them.
