Backend Token Authentication, Rate Limiting, and Anonymous Access Design
This article explains a comprehensive backend user login flow, covering token generation, expiration policies, request validation, logout handling, anonymous access strategies, rate‑limiting with authorized tokens, path‑regex filtering, blacklist management, and includes a Spring‑Redis implementation example.
Introduction
This article introduces the user login process and its technical implementation through diagrams and code, covering login, verification, token handling, blacklist, and anonymous request bypass mechanisms, with reference to gateway concepts.
Business Diagram
A flowchart illustrates how new and existing users are processed during registration and login.
Process Explanation
Client – Login Interface (typically 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 (initialize if not)
Generate token after successful verification
Return token to client
User Information Design
Diagram showing the structure of stored user information.
Token Expiration Time
Token lifetimes differ by client type: mobile apps may have a week‑long validity, while web tokens expire after a few hours; separate interfaces or header checks can differentiate the two.
Business Request Token Validation
After login, each client request carries the token, which a gateway validates against a cache keyed by the token containing basic user data, enabling downstream services to retrieve user ID, account, and nickname from request headers.
Logout Operation
The client calls a logout endpoint; the server deletes the token cache entry and returns a 401 response, prompting the client to redirect to the login page.
Anonymous Requests (No Login)
Two common approaches for allowing anonymous access: (1) authorized token with request‑rate limits, or (2) path‑regex rules that whitelist certain endpoints.
Solution 1: Authorized Token with Rate Limiting
Advantages: traceability of actions and controllable request frequency; Disadvantages: additional coding and configuration effort.
Technical Implementation
Provide a management page for authorized tokens, specifying token value and allowed requests per minute.
CRUD operations store tokens in a cache using a map where the key is the token and the value is the request limit.
Cache entries expire after one minute to enforce the time window.
Code example for request‑count checking:
import org.springframework.beans.factory.annotation.Autowired;<br/>import org.springframework.data.redis.core.RedisTemplate;<br/>import org.springframework.stereotype.Component;<br/><br/>import java.util.concurrent.TimeUnit;<br/><br/>/**<br/> * Authorized token request limit cache<br/> *<br/> * @author 热黄油啤酒<br/> * @since 2021-11-01<br/> */<br/>@Component<br/>public class AuthTokenRequestLimitCache {<br/><br/> @Autowired<br/> private RedisTemplate<String, Integer> redisTemplate;<br/><br/> private static final String AUTH_TOKEN_LIMIT_KEY_PREFIX = "auth_token_limit";<br/><br/> /**<br/> * Increment request count and check if it exceeds the limit<br/> * @param token<br/> * @return whether the request is allowed<br/> */<br/> public boolean incrementWithCheck(String token) {<br/> // 1. Get the request limit for the token; null means the token is no longer authorized<br/> Integer limit = getLimit(token);<br/> if (limit == null) {<br/> return false;<br/> }<br/> // 2. Build cache key and read current count<br/> String key = String.join(":", AUTH_TOKEN_LIMIT_KEY_PREFIX, token);<br/> Integer count = redisTemplate.opsForValue().get(key);<br/> // 3. If no count exists, initialize it with a 1‑minute expiration<br/> if (count == null) {<br/> redisTemplate.opsForValue().increment(key);<br/> redisTemplate.expire(key, 1L, TimeUnit.MINUTES);<br/> return true;<br/> }<br/> // 4. Increment and compare with limit; return false if exceeded<br/> Long inc = redisTemplate.opsForValue().increment(key);<br/> return inc <= limit;<br/> }<br/><br/> /**<br/> * Retrieve the configured limit for a token<br/> * @param token<br/> * @return limit value or null<br/> */<br/> public Integer getLimit(String token) {<br/> Object limit = redisTemplate.opsForHash().get("auth_token_limit", token);<br/> return limit == null ? null : (Integer) limit;<br/> }<br/>}<br/>Typically, only GET operations are permitted on the authorized token endpoint; data modification is usually disallowed at the business layer.
Solution 2: Request Path Regex Validation
Configure anonymous interface rules in the gateway configuration; incoming requests matching the regex are allowed without token verification, otherwise normal token checks apply.
Blacklist
Implement a blacklist as a final security layer: add user IDs to a Redis set via an admin UI, reject login attempts for blacklisted users, and if a logged‑in user is blacklisted, delete their token cache and return a 401 response.
Conclusion
The user system is a fundamental component; this article provides a thorough overview of login flows, token management, rate limiting, anonymous access, and blacklist strategies for backend developers.
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.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.
