Designing Secure User Login with Token Management & Rate Limiting in Spring Boot

This article explains a complete user login workflow—including registration, verification, token generation, expiration policies, gateway validation, logout, anonymous access, rate‑limiting, and blacklist handling—illustrated with diagrams and a Spring Boot implementation using Redis.

Architect's Guide
Architect's Guide
Architect's Guide
Designing Secure User Login with Token Management & Rate Limiting in Spring Boot

Introduction

This article introduces a user login process and its technical implementation, covering login, verification, token acquisition, blacklist handling, and anonymous request strategies.

Business Diagram

The login flow involves user registration and verification, as shown in the diagram.

Process Interpretation

Client – Login Interface (usually mobile SMS verification)

Enter phone number

Send verification code

Enter verification code

Check "auto‑register new user" if needed

Server – User Verification

Validate phone number and code

Check if user exists (create if not)

Generate token after successful verification

Return token to client

User Information Design

Verification Flow Diagram

The login verification involves two APIs and two caches: a verification‑code API that sends a code and stores it with an expiration, and a login API that checks the cached code, generates a token on success, and returns it to the client for subsequent authenticated requests.

Token Expiration

Token lifetime is usually defined by client type: mobile apps may have a week‑long expiration, while web tokens expire in hours. You can separate app and web login endpoints or decide based on request‑header information.

Business Request Token Validation

After login, each client request carries the token. A gateway validates the token using a cache that stores basic user information, as illustrated below.

Upon successful validation, the gateway rewrites internal request headers to include the user’s ID, account, and nickname, facilitating downstream services to obtain the current user and enforce permission checks.

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.

Anonymous Requests (No Login)

Two common approaches for allowing anonymous access: (1) issue an authorized token with a request‑rate limit, or (2) configure path‑regex rules in the gateway to whitelist certain endpoints.

Solution 1: Authorized Token with Rate Limiting

Pros: even without login, actions can be traced and request frequency is controllable, preventing abuse. Cons: requires additional coding and configuration.

Technical Implementation

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

CRUD operations store tokens in a cache (e.g., a map where the key is the token and the value is the request limit).

Use a per‑minute counter cache with a one‑minute expiration.

The verification flow diagram is extended to incorporate this rate‑limiting step.

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 the token is no longer authorized
        Integer limit = getLimit(token);
        if (limit == null) {
            return false;
        }
        // 2. Build cache key and read current count
        String key = String.join(":", AUTH_TOKEN_LIMIT_KEY_PREFIX, token);
        Integer count = redisTemplate.opsForValue().get(key);
        // 3. If no count, initialize it
        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;
    }

    /**
     * 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‑modifying actions are usually prohibited.

Solution 2: Path Regex Validation

Add anonymous‑interface rules to the gateway configuration. When a request arrives, the gateway checks whether the path matches a whitelist pattern; if it does, the request is allowed without token verification, otherwise normal token validation is performed.

Blacklist

A blacklist serves as the final security barrier. Implementation steps:

Provide a “block user” button in the user‑management UI; blocked user IDs are stored in a Redis set.

During login, check if the user ID exists in the blacklist; if so, reject the login.

If a logged‑in user is later blacklisted, the gateway removes the associated token cache after authentication and returns a 401, causing the client to redirect to the login page.

Conclusion

The user system is a foundational component; this article gives developers a comprehensive view of login workflows and related features such as token handling, rate limiting, logout, anonymous access, and blacklist management.

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.

BackendSpring BootAuthenticationgatewayToken
Architect's Guide
Written by

Architect's Guide

Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.

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.