In this chapter, we used GoFrame
to complete the management of user sessions, providing the two major features of login and user information retrieval, deepening our understanding of GoFrame
and learning the following content:
- Declare a user struct to generate
Token
; - Parse
Token
to extract user information and provide a user information retrieval interface; - Basic usage of middleware to complete user permission authentication;
- Register middleware in grouped routing.
About Logging Out
Why didn't we develop a logout feature? This is because JWT
is essentially a stateless token, and once issued, the server does not store it. This means that when using JWT
, logging out cannot be as simple as destroying a session on the server-side as in traditional sessions. There are roughly two solutions for handling JWT
logout, each with its pros and cons:
-
Blacklist Mechanism:
- When a user logs out or the
JWT
is revoked, add the token to a blacklist database; - With each request, extract the
JWT
from the request header and check if it's in the blacklist; - If the token is in the blacklist, deny the request;
- Its advantage lies in ease of implementation and maintenance, suitable for most cases; the disadvantage is the necessity to store all revoked tokens, which may lead to increased storage space.
- When a user logs out or the
-
Whitelist Mechanism:
- Upon user login, add the generated
JWT
to a whitelist database; - With each request, extract the
JWT
from the request header and check if it's in the whitelist; - If the token is not in the whitelist, deny the request.
- Its advantage lies in higher security, as only tokens on the whitelist are accepted, ensuring stricter access control. The downside is increased complexity, requiring tokens to be added to the whitelist upon login and removed at the appropriate time.
- Upon user login, add the generated
Typically, blacklist and whitelist data are stored in non-relational databases, such as Redis
.