User Login Flow, Token Management, and Anonymous Access Implementation in a Java Backend

This article explains the complete user login process, token generation and validation, token expiration policies, logout handling, and two approaches for anonymous requests—authorized tokens with rate limiting and path‑based regex rules—illustrated with diagrams and Java/Redis code examples.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
User Login Flow, Token Management, and Anonymous Access Implementation in a Java Backend

Introduction

This article uses diagrams and code to describe the user login process, including login, verification, user information retrieval, blacklist handling, and anonymous request implementations.

Business Diagram

The login flow involves user registration and verification, handling both new and existing users.

Flow Interpretation

Client – Login Interface (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 (initialize if not)

Generate token after verification

Return token to client

User Information Design

Verification Flow Diagram

The login verification involves two APIs and two caches: one for sending verification codes (with expiration) and another for login, which reads the cache, validates, generates a token, and returns it to the client.

Token Expiration

Token lifetime depends on client type: mobile apps usually a week, web clients a few hours; you can separate app and web login endpoints or decide based on request headers.

Business Request Token Validation

After login, each client request carries the token; a gateway validates the token, retrieves user basic info from cache, and injects user ID, account, and nickname into request headers for downstream services.

Logout Operation

The client calls a logout API; the API deletes the token cache and returns HTTP 401, prompting the client to redirect to the login page.

Anonymous Request (No Login)

Two common solutions: (1) authorized token with request‑rate limits; (2) path‑based regex rules that allow certain endpoints to bypass token verification.

Solution 1: Authorized Token with Rate Limiting

Advantages: traceable operations and controllable request frequency; Disadvantages: additional coding and configuration.

Technical Implementation

Provide a management page for authorized tokens, storing token value and allowed requests per minute.

Store token data in a cache (e.g., Redis) using a map where the key is the token and the value is the request limit.

Use a one‑minute expiration cache for counting requests.

Upgrade the verification flow diagram 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 limit
     *
     * @param token
     * @return whether to allow
     */
    public boolean incrementWithCheck(String token) {
        // 1. Get limit; null means token 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
        if (count == null) {
            redisTemplate.opsForValue().increment(key);
            redisTemplate.expire(key, 1L, TimeUnit.MINUTES);
            return true;
        }
        // Increment and compare with limit
        Long inc = redisTemplate.opsForValue().increment(key);
        return inc <= limit;
    }

    /**
     * Get limit for a token
     */
    public Integer getLimit(String token) {
        Object limit = redisTemplate.opsForHash().get("auth_token_limit", token);
        return limit == null ? null : (Integer) limit;
    }
}

Authorized APIs typically allow only GET operations; updates are usually prohibited at the business layer.

Solution 2: Path Regex Validation

Add anonymous endpoint rules to the gateway configuration; the gateway checks request paths against these regex rules and either bypasses token verification or proceeds with normal authentication.

Blacklist

Provide a “block user” button in the user‑management page; blocked user IDs are stored in a Set.

During login, check if the user is in the blacklist and reject if so.

If a logged‑in user is blocked, the gateway removes the token cache after authentication and returns HTTP 401, forcing a re‑login.

Conclusion

The user system is fundamental, and many developers may not have participated in its development; this article offers a comprehensive overview of login flow, token handling, logout, anonymous access, and blacklist mechanisms.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

SecurityAuthenticationgatewayToken
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.