Token Introduction
The term "token" refers to a "pass," which is a string generated by the server serving as an identifier for client requests. It acts as the credential required when accessing resource interfaces (APIs).
- uid (User's unique identity identifier)
- time (Timestamp representing the current time)
- sign (Signature: The first few characters of the token are compressed into a fixed-length hexadecimal string using a hashing algorithm)
Characteristics of Tokens
- Stateless on the server side, with good scalability.
- Supports mobile devices.
- Secure.
- Supports cross-program invocation.
Token Authentication Flow
- The client requests login using username and password.
- Upon receiving the request, the server verifies the username and password.
- Upon successful verification, the server issues a token and sends it to the client.
- After receiving the token, the client stores it locally (e.g., in cookies or localStorage).
- Every time the client requests resources from the server, it must include the issued token.
- The server receives the request, verifies the token included in the client's request; if verification succeeds, it returns the requested data to the client.
Considerations When Using Tokens
If you believe storing tokens in a database will result in excessive query times, consider storing them in memory instead (e.g., Redis is well-suited for your token lookup requirements).
Since tokens are entirely managed by the application, they can bypass same-origin policy restrictions.
Tokens help avoid CSRF attacks (as cookies are no longer required).
Mobile devices have limited support for cookies, while sessions rely on cookie implementation; therefore, mobile applications commonly use tokens.
Refresh Token
Another type of token—the refresh token.
The refresh token is specifically designed to renew the access token. Without a refresh token, an access token can still be renewed, but this requires re-entering login credentials (username and password) every time, which is cumbersome. With a refresh token available, clients can directly use it to update their access tokens without requiring additional user operations.
The validity period of an Access Token is relatively short; when the Access Token expires or becomes invalid due to expiration, a Refresh Token can be used to obtain a new one. If the Refresh Token also expires, the user must log in again.
Refresh Tokens and their expiration times are stored in the server's database. They are only validated when applying for a new Access Token; this process does not affect business interface response times nor requires keeping them continuously resident in memory like Sessions to handle high volumes of requests.