Doing user authentication with JWT is a relatively simple way.
Common authentication methods
The mainstream methods of user authentication are broadly classified as session-based and token-based. User authentication with JWT
sesion-based authentication method
- User sends username and password to the server.
- The server authenticates and saves relevant data in the current conversation (sesion), such as user role, login time, etc.
- The server returns a session_id to the user, which is written to the user’s cookie or other storage.
- Each subsequent request from the user will send the session_id back to the server via a cookie.
- The server receives the session_id, finds the pre-saved data, and thus learns the user’s identity.
- The user logs out and the server clears the data corresponding to the session_id.
In this way, the server needs to save the session_id and related data to be verified when receiving a user request, for example, to Redis.
token-based authentication method
- User sends username and password to the server.
- The server signs the relevant data, such as user ID, authentication expiration date, etc., and then generates a token and returns it to the client.
- The client writes the token to local storage.
- The token is appended to the header for each subsequent request from the user.
- The server gets the header of the user request, gets the user data and does signature verification. If the verification is successful, it means the data has not been tampered with and is valid.
jwt is one of the token-based authentication methods. Here we use jwt-go to use jwt in our Golang project. The following code is sample code, some of the content has been trimmed for reference only.
Generate Token
The server side needs to provide a login interface for user login. The client provides the user name and password, the server checks them, and if they pass the check, the Token is generated and returned to the client.
|
|
Checking Token
Here the client is required to set the token obtained through the login interface in the Authorization
header of the sent request each time.
|
|
Points to note
- Since the data in the Token returned by jwt is only Base64 processed and not encrypted, no important information should be put in it.
- Since jwt Token is stateless, anyone who gets this Token can access it, so to reduce theft, you can set the Token validity period to be shorter. For some important operations, try to authenticate again.
- Use HTTPS as much as possible to reduce the leakage of Token.