MQTT-based token authentication service method and system
Patent Information
- Application Number
- CN202611121612.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-27
- Publication Date
- 2026-10-16
AI Technical Summary
[0007]本发明的目的在于,提供一种基于MQTT的Token认证服务方法及系统,能够有效克服现有认证技术存在的同步阻塞瓶颈、会话状态管理复杂、认证模块复用性差和Token生命周期管理缺失的技术缺陷
(1)传统HTTP认证接口在高并发场景下,服务端线程资源与客户端连接绑定,服务端线程资源被大量占用,并发请求量受限于线程池大小,系统扩展性差,响应延迟增加,易成为系统性能瓶颈;本发明采用异步解耦,高并发支撑能力强:利用MQTT的发布订阅模型实现认证流程的完全异步化,服务端无需维护大量阻塞连接,可支撑百万级设备并发认证请求
Smart Images

Figure CN122933010A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the fields of computer network security and identity authentication technology, specifically to a token authentication service method and system based on MQTT. Background Technology
[0002] In IoT and distributed application systems, the number of client devices is large and the network environment is complex. Traditional authentication methods have the following drawbacks: 1. Synchronous Blocking Bottleneck: Traditional HTTP-based authentication interfaces use a synchronous request-response model, where the server needs to maintain the connection until the response is complete while processing authentication requests. In high-concurrency scenarios, server-side thread resources are heavily consumed, and response latency increases significantly. When concurrent requests exceed the system's capacity, the server is prone to a cascading failure, causing the entire authentication service to become unavailable and impacting the business experience.
[0003] 2. Distributed Session State: With traditional session persistence mechanisms, the server needs to maintain session state for each online client. In a distributed deployment architecture, session state needs to be synchronized across multiple service nodes, increasing system complexity and making it difficult to guarantee state consistency. When a service node fails, all session state maintained by that node is lost, impacting user experience.
[0004] 3. Coupling of Authentication and Business Functions: Most application systems embed authentication logic directly into business service code. This makes the authentication module difficult to reuse, and each business request requires repeated authentication, increasing the server load. When upgrading the authentication algorithm or adding authentication factors, all business services need to be modified, resulting in high maintenance costs and the potential introduction of new security vulnerabilities.
[0005] 4. Risks in credential transmission: Simple username and password authentication is vulnerable to interception when there is no encrypted transmission, posing a security risk.
[0006] Therefore, there is a need for an authentication service solution that is asynchronous, decoupled, has timely management capabilities, and is secure and reliable. Summary of the Invention
[0007] The purpose of this invention is to provide a token authentication service method and system based on MQTT, which can effectively overcome the technical defects of existing authentication technologies, such as synchronous blocking bottlenecks, complex session state management, poor reusability of authentication modules, and lack of token lifecycle management.
[0008] The first technical solution adopted by this invention is: a token authentication service method based on MQTT, comprising the following steps: S1: The client initiates an asynchronous authentication request; the client constructs an authentication request data packet carrying user credentials and publishes the request data packet to the preset authentication request topic via the MQTT protocol; S2: Server-side verification and issuance; The server, as a high-priority consumer, subscribes to the authentication request topic, receives and parses the authentication request, verifies the user's credentials, generates a time-sensitive token after successful verification, and publishes an authentication response message containing the token and its validity period to the private receipt topic associated with the client. S3: The client obtains the token; after initiating the authentication request, the client subscribes to the private receipt topic published by the server, receives the authentication response asynchronously through the MQTT message broker, parses and caches the token, and uses it for subsequent access authentication of business interfaces; S4: Token lifecycle management; each time a client accesses a business service with a token, the server verifies the token's validity and expiration time; when the token expires, the server automatically updates the token.
[0009] Furthermore, in step S2, the server adopts a producer-consumer thread architecture; upon receiving an authentication request, the threads in the worker thread pool concurrently process the credential verification; after successful verification, the generated Token is stored in the database table and an expiration time is set.
[0010] Furthermore, in step S4, the specific process of the server automatically updating the Token includes: when the Token expires, the server issues a new Token to the client, that is, the client's Token becomes invalid and cannot verify the identity in subsequent business requests; after the Token expires, the client's original access credentials become invalid, and all business requests carrying the expired Token will be rejected by the server.
[0011] The second technical solution adopted by this invention is: a token authentication service system based on MQTT, comprising: The client authentication module, embedded in business applications, includes a credential management unit, an MQTT publishing unit, a receipt listening unit, and a first token caching unit. The credential management unit stores and manages the user's original credentials, encapsulating them into an MQTT message payload when initiating an authentication request. The MQTT publishing unit maintains a long connection with the message broker. The receipt listening unit subscribes to private receipt topics and asynchronously receives authentication results from the server. The first token caching unit caches received valid tokens in local memory or client storage for quick retrieval by business applications and appending to subsequent business requests, avoiding duplicate authentication. The server-side authentication module, deployed on a central server, includes a subscription listening unit, a receipt publishing unit, and a second token caching unit. The subscription listening unit directly receives authentication requests from all clients from the message broker. The receipt publishing unit encapsulates the generated token and login result into a receipt topic published to the corresponding client. The second token caching unit stores the issued token in a database for subsequent token verification and lifecycle management by the business server, and is a server-level global storage.
[0012] The beneficial effects of this invention are as follows: (1) In high-concurrency scenarios, traditional HTTP authentication interfaces bind server-side thread resources to client connections, resulting in a large amount of server-side thread resources being occupied. The number of concurrent requests is limited by the thread pool size, leading to poor system scalability, increased response latency, and a tendency to become a system performance bottleneck. This invention adopts asynchronous decoupling and has strong high-concurrency support capabilities: it utilizes the publish-subscribe model of MQTT to achieve a completely asynchronous authentication process. The server does not need to maintain a large number of blocking connections, and it can support millions of concurrent authentication requests from devices. (2) Traditional authentication methods lack a unified token issuance, verification, and refresh mechanism, which has security vulnerabilities. This invention establishes a closed loop for token issuance, verification, and refresh management, effectively preventing token abuse and leakage risks, achieving effective lifecycle management, and ensuring high security. (3) Session-based session persistence mechanisms require the introduction of additional state synchronization middleware in a distributed environment, which is costly and increases system complexity and maintenance costs, and also poses a single point of failure risk. This invention, based on Token role information and topic mechanism, enables clients to achieve fine-grained access control to specific resources, which can achieve fine-grained permission control, strong resource isolation, and meet the needs of multi-tenant and multi-permission scenarios. Attached Figure Description
[0013] To more clearly illustrate the technical solutions in the embodiments of the present invention, the drawings used in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of this application. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0014] Figure 1 This is a system architecture diagram of an example of the present invention; Figure 2 This is a flowchart illustrating the asynchronous authentication request process for the client in an example of the present invention. Figure 3 This is a flowchart illustrating the token lifecycle management process in an example of the present invention. Detailed Implementation
[0015] To better understand the above-described objects, features, and advantages of the present invention, the invention will be further described in detail below with reference to the accompanying drawings and specific embodiments. Many specific details are set forth in the following description to provide a thorough understanding of the invention; however, the invention may be practiced in other ways different from those described herein, and therefore, the invention is not limited to the specific embodiments disclosed below.
[0016] like Figure 1 As shown, this embodiment of the invention provides a token authentication service system based on MQTT, including: The client authentication module, embedded in business applications, includes a credential management unit, an MQTT publishing unit, a receipt listening unit, and a first token caching unit. The credential management unit stores and manages original user credentials (such as username and password), encapsulating them into an MQTT message payload when initiating an authentication request. The MQTT publishing unit maintains a long-lived connection with the message broker. The receipt listening unit subscribes to private receipt topics and asynchronously receives authentication results from the server. The first token caching unit caches received valid tokens in local memory or client storage for quick retrieval by business applications and appending to subsequent business requests, avoiding duplicate authentication.
[0017] In this embodiment of the invention, the client authentication module adopts a layered design, with the bottom layer being a cross-platform C++ library and the upper layer adapting to different business frameworks.
[0018] MQTT Connection and Topic Subscription: The client manages MQTT connections through the `LoginInWindow` class. In the `judge` function, the client's username, password, and IP address are encapsulated using the `CMqttMsgLoginReq` class, packaged, and a connection is established with the MQTT broker. Upon successful connection, the client automatically subscribes to its reply topic, named "login," ensuring that response messages are received by the client.
[0019] Receipt Listening and Asynchronous Result Processing: When the server sends the authentication result, the client waits for the topic message to arrive through the SignalProcessForLogin callback function in the MQTTForLogin class, which then triggers the onReceiveLoginMsg function. First, the message format is validated to filter out unexpected payloads. After successful validation, the message is transformed into a CMqttMsgLoginResult object, which contains m_bRes (authentication result), m_szToken (generated token), etc. Based on the authentication result, branching processing occurs: if the result is non-zero, the CMgrCurUser global management class writes the token to the secure storage area and sets m_IsRight (login result) to true, indicating successful authentication; if the result is zero, authentication fails, and no further processing is performed.
[0020] Token caching management: After successful authentication, the client persists the token issued by the server and its expiration time to local secure storage. Each time the client starts, it first reads the local token and verifies its validity using the local time.
[0021] The server-side authentication module, deployed on a central server, includes a subscription listening unit, a receipt publishing unit, and a second token caching unit. The subscription listening unit directly receives authentication requests from all clients from the message broker. The receipt publishing unit encapsulates the generated token and login result into a receipt topic published to the corresponding client. The second token caching unit stores the issued token in a database for subsequent token verification and lifecycle management by the business server, and is a server-level global storage.
[0022] In this embodiment of the invention, the server-side authentication module adopts a microservice architecture, with the core authentication service deployed independently and communicating decoupled from the client.
[0023] Token Caching and Refresh Mechanism: After successful token issuance, to ensure effective management and security of the authentication state, the system not only relies on the client's storage of the token but also performs strict state synchronization on the server side using the StoreTokenValue function. Specifically, when... TokenDuring token generation, the StoreTokenValue function extracts a unique identifier from the token, such as a user ID, and stores the user ID as the key in the server's database. It also sets an expiration time for this key that matches the token's own. This allows the server to proactively track the lifecycle of each token and promptly invalidate specific tokens when necessary, effectively preventing token misuse or replay attacks. This mechanism not only enhances system security but also provides a reliable foundation for unified session management.
[0024] Receipt Publishing Unit: During the MQTT login authentication process on the server side, the system first calls the `generateToken` function in the `SimpleTokenManager` class to generate a globally unique token string as the authentication identifier for the current session. Subsequently, the server integrates the generated token with the authentication result, encapsulating them together into a `CMqttMsgLoginResult` object. This object is specifically designed to carry the message structure for the login response data, containing all the authentication information required for subsequent client communication. After encapsulation, the server publishes the `CMqttMsgLoginResult` object to the corresponding response topic via the MQTT protocol, thereby pushing the login result to the client in real time. This process not only ensures the secure issuance of the token but also provides a standardized credential for subsequent client requests, achieving a complete closed-loop transmission of authentication information.
[0025] like Figure 2 and Figure 3 As shown in the figure, this embodiment of the invention also provides a token authentication service method based on MQTT, including the following steps: S1: The client initiates an asynchronous authentication request; the client constructs an authentication request data packet carrying user credentials and publishes the request data packet to the preset authentication request topic via the MQTT protocol.
[0026] S2: Server-side verification and issuance; The server, as a high-priority consumer, subscribes to the authentication request topic, receives and parses the authentication request, verifies the user's credentials, generates a time-sensitive token after successful verification, and publishes an authentication response message containing the token and its validity period to the private receipt topic associated with the client.
[0027] In step S2, the server adopts a producer-consumer thread architecture; when an authentication request is received, the threads in the worker thread pool concurrently process the credential verification; after the verification is successful, the generated Token is stored in the database table and an expiration time is set.
[0028] S3: The client obtains the token; after initiating an authentication request, the client subscribes to the private receipt topic published by the server, receives the authentication response asynchronously through the MQTT message broker, parses and caches the token, and uses it for subsequent access authentication of business interfaces.
[0029] S4: Token lifecycle management; each time a client accesses a business service with a token, the server verifies the token's validity and expiration time; when the token expires, the server automatically updates the token.
[0030] In step S4, the specific process of the server automatically updating the token includes: when the token expires, the server issues a new token to the client, that is, the client token becomes invalid and cannot verify the identity in subsequent business requests; after the token expires, the client's original access credentials become invalid, and all business requests carrying the expired token will be rejected by the server.
[0031] The core processing mechanism of this invention embodiment is as follows: (1) Client asynchronous authentication request and private receipt mechanism The client uses lightweight components to encapsulate the authentication logic and publishes authentication requests carrying user credentials to a pre-defined authentication request topic via the MQTT protocol. After initiating authentication, the client subscribes to this topic and receives the authentication result from the server asynchronously. This mechanism decouples authentication requests and responses, avoiding synchronous blocking and waiting. This invention eliminates traditional synchronous blocking authentication interactions and utilizes MQTT's asynchronous publish / subscribe model to decouple and smooth out peak / valley conditions in the authentication process. This solves the problem of authentication services easily becoming performance bottlenecks in high-concurrency scenarios, improving the scalability and response speed of the authentication system.
[0032] Token lifecycle process management mechanism (2) The system has established a token lifecycle management process: Issuance phase: The server stores the generated token in the database table and sets the expiration time, while also recording the mapping relationship between the token and the client; Verification phase: When the business service receives a request carrying a token, it verifies the validity of the signature and the validity of the time. Refresh phase: When the client's token expires, the server requests a new token value and issues a new token.
[0033] Topic isolation and access control mechanism (3) The system adopts a topic isolation strategy: the authentication request topic can only be subscribed to by the server; the subscription permission of the private receipt topic is limited to the corresponding client. The server configures the permissions when issuing the token to ensure that the authentication response can only be received by the target client. At the same time, it supports publish-subscribe permission control based on token role information to achieve fine-grained resource access management.
[0034] The above description is merely a preferred embodiment of the present invention and is not intended to limit the invention. Various modifications and variations can be made to the present invention by those skilled in the art. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.
Claims
1. A token authentication service method based on MQTT, characterized in that, Includes the following steps: S1: The client initiates an asynchronous authentication request; the client constructs an authentication request data packet carrying user credentials and publishes the request data packet to the preset authentication request topic via the MQTT protocol; S2: Server-side verification and issuance; The server, as a high-priority consumer, subscribes to the authentication request topic, receives and parses the authentication request, verifies the user's credentials, generates a time-sensitive token after successful verification, and publishes an authentication response message containing the token and its validity period to the private receipt topic associated with the client. S3: The client obtains the token; after initiating the authentication request, the client subscribes to the private receipt topic published by the server, receives the authentication response asynchronously through the MQTT message broker, parses and caches the token, and uses it for subsequent access authentication of business interfaces; S4: Token lifecycle management; each time a client accesses a business service with a token, the server verifies the token's validity and expiration time; when the token expires, the server automatically updates the token.
2. The MQTT-based token authentication service method according to claim 1, characterized in that, In step S2, the server adopts a producer-consumer thread architecture; when an authentication request is received, the threads in the worker thread pool concurrently process the credential verification; after the verification is successful, the generated Token is stored in the database table and an expiration time is set.
3. The MQTT-based token authentication service method according to claim 1, characterized in that, In step S4, the specific process of the server automatically updating the token includes: when the token expires, the server issues a new token to the client, that is, the client token becomes invalid and cannot verify the identity in subsequent business requests; after the token expires, the client's original access credentials become invalid, and all business requests carrying the expired token will be rejected by the server.
4. A token authentication service system based on MQTT, characterized in that, include: The client authentication module, embedded in business applications, includes a credential management unit, an MQTT publishing unit, a receipt listening unit, and a first token caching unit. The credential management unit stores and manages the user's original credentials, encapsulating them into an MQTT message payload when initiating an authentication request. The MQTT publishing unit maintains a long connection with the message broker. The receipt listening unit subscribes to private receipt topics and asynchronously receives authentication results from the server. The first token caching unit caches received valid tokens in local memory or client storage for quick retrieval by business applications and appending to subsequent business requests, avoiding duplicate authentication. The server-side authentication module is deployed on the central server and includes a subscription listening unit, a receipt publishing unit, and a second token caching unit. The subscription listening unit is used to directly receive authentication requests from all clients from the message broker; the receipt publishing unit is used to encapsulate the generated token and login result into a receipt topic to be published to the corresponding client; the second token caching unit stores the issued token in the database for subsequent token verification and lifecycle management by the business server, which is a server-level global storage.