User Login & Token Management: Flow, Rate Limiting, and Security
This article explains the complete user login process, from mobile verification and automatic registration to token generation, validation, expiration policies, logout handling, anonymous access strategies, rate‑limiting via authorized tokens, path‑regex checks, and blacklist management, illustrated with diagrams and Java‑Spring code examples.
Preface
This article introduces the user login flow and its technical implementation through diagrams and code, covering login, verification, how to obtain user information, and handling of blacklist and anonymous interfaces.
Business Diagram
The login process involves user registration and verification; the diagram shows how new and existing users are handled.
Flow Interpretation
Client – Login screen (usually mobile SMS verification)
Enter phone number
Send verification code
Enter verification code
Check "auto‑register new user"
Server – User verification
Validate phone number and code
Check if user exists (create initial info if not)
Generate token after verification
Return token to client
User Information Design
Verification Flow Diagram
The login verification involves two interfaces and two caches: (1) a verification‑code endpoint that sends a code to the phone and stores it with an expiration time; (2) a login endpoint that reads the cache, validates the code, generates a token, and returns it. Subsequent requests carry the token in the header.
About Token Expiration Time
Token expiry is usually defined by client type: mobile apps may have a week‑long expiry, while web tokens expire in hours. You can separate app and web login into different endpoints or decide based on request headers.
About Business Request Token Verification
After login, each client request includes the token. A gateway validates the token by looking up the cached user information and injects user ID, account, and nickname into request headers for downstream services.
Upon successful verification, the gateway rewrites internal request headers with user details to simplify permission checks.
About Logout Operation
The client calls a logout endpoint; the server deletes the token’s cache entry and returns a 401 response, prompting the client to redirect to the login page.
About Anonymous Requests (No Login)
Two common approaches: (1) authorized token with request‑rate limits; (2) path‑regex rules that whitelist certain endpoints.
Solution 1: Authorized Token with Rate Limiting
Advantages: even without login, actions are traceable and request volume is controllable, preventing abuse. Disadvantages: requires additional coding and configuration.
Technical Implementation
Provide a management page for authorized tokens, storing token value and allowed requests per minute (e.g., 60).
CRUD operations store tokens in a cache (map) with token as key and request limit as value.
Use a one‑minute expiration cache for counting requests.
The verification flow diagram is upgraded accordingly.
Request Count Check Code Implementation
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* Authorized token request limit cache
*
* @author 热黄油啤酒
* @since 2021-11-01
*/
@Component
public class AuthTokenRequestLimitCache {
@Autowired
private RedisTemplate<String, Integer> redisTemplate;
private static final String AUTH_TOKEN_LIMIT_KEY_PREFIX = "auth_token_limit";
/**
* Increment request count and check if it exceeds the limit
*
* @param token token value
* @return whether the request is allowed
*/
public boolean incrementWithCheck(String token) {
// 1. Get limit; null means token is no longer authorized
Integer limit = getLimit(token);
if (limit == null) {
return false;
}
// 2. Build cache key and read count
String key = String.join(":", AUTH_TOKEN_LIMIT_KEY_PREFIX, token);
Integer count = redisTemplate.opsForValue().get(key);
// 3. If no count, initialize and set 1‑minute expiry
if (count == null) {
redisTemplate.opsForValue().increment(key);
redisTemplate.expire(key, 1L, TimeUnit.MINUTES);
return true;
}
// 4. Increment and compare with limit
Long inc = redisTemplate.opsForValue().increment(key);
return inc <= limit;
}
/**
* Retrieve the configured limit for a token
*
* @param token token value
* @return limit or null
*/
public Integer getLimit(String token) {
Object limit = redisTemplate.opsForHash().get("auth_token_limit", token);
return limit == null ? null : (Integer) limit;
}
}Authorized interfaces typically allow only GET operations; data modification is usually prohibited.
Solution 2: Path Regex Validation
Add anonymous interface rules to the gateway configuration; the gateway checks if the request path matches the whitelist and either allows it or proceeds with token verification.
About Blacklist
The blacklist serves as the final security gate. Implementation steps:
Provide a “blacklist” button in the user‑management UI; selected user IDs are stored in a Redis set.
During login, check if the user is in the blacklist and reject if so.
If a logged‑in user is blacklisted, the gateway deletes the associated token cache and returns 401, forcing the client to the login page.
Summary
The user system is a fundamental component; many developers may not have built one from scratch. This article offers a comprehensive overview of the login workflow and related features such as token handling, rate limiting, anonymous access, and blacklist management.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
