In this chapter, we need to complete the user session management functions:
- Login;
- Retrieve user information.
Introduction to JWT
HTTP
is a stateless protocol, meaning every request is independent with no contextual relationship. This requires a mechanism to preserve user state information, and Cookie
is one of such solutions. Cookies
are small pieces of data stored in the user's browser that can be sent to the server in subsequent requests to maintain session state. However, Cookies
have some limitations, such as cross-domain issues and security concerns. In contrast, JWT
is a more modern solution that can be transmitted through the HTTP
header without relying on Cookies
and offers better cross-domain support and security.
JWT
, or Json Web Token
, appears as a string of unordered characters. It consists of three parts: Header, Payload, and Signature.
In projects with frontend-backend separation, after a user logs in, the server generates a JWT
and returns it. The client saves it independently, for example, in the browser's local storage Local Storage
. In subsequent requests, it is typically included in the Authorization
field of the Header
to complete user authentication.
Install golang-jwt
Generating and verifying JWT
requires complex encryption and decryption logic, which can be cumbersome to write yourself. Fortunately, others have already created this tool, and you can directly install and use it.
$ go get -u github.com/golang-jwt/jwt/v5