NOTE
JWT
Historical JWT notes covering what JWT is, why it is used, JWT versus sessions, token structure, and the basic request flow.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What Is JWT
- A token issued by the server to a user after the user has authenticated successfully.
- A token is a credential valid for a certain period of time, indicating that the user has been authenticated.
2. Why JWT Is Needed
- Used for cross-domain authentication.
- Cross-domain authentication means that if a company has two domains A and B, after a user authenticates on domain A, the user does not need to authenticate again when accessing domain B.
- Traditional cross-domain authentication uses the cookie + session mechanism: the cookie stores the session-id, and the server persists the session.
- JWT is a client-side solution: all data is stored on the client and sent back to the server with every request.
2.1. JWT vs. Session
- JWT is a client-side solution, while session is a server-side solution.
- The server-side solution is more secure.
- The server can revoke a session at any time.
- The server is stateful, so scaling is more troublesome.
- JWT is a self-describing token.
- Traditional token: after a resource service receives the token, it needs to request the authorization server to validate the token.
- JWT: after a resource service receives the token, it can validate it itself [because there is a signature].
3. JWT Principle
- The client requests authentication from the server.
- After authenticating the user, the server writes non-sensitive data into the JWT and returns it to the client.
- The JWT structure is as follows:
Header.Payload.Signature- Header: a JSON object describing JWT metadata. It is converted to a string using the Base64URL algorithm.
{ "alg": "HS256", "typ": "JWT" } - Payload: a JSON object used to store the actual data that needs to be transmitted. It is converted to a string using the Base64URL algorithm.
iss (issuer): issuer exp (expiration time): expiration time sub (subject): subject aud (audience): audience nbf (Not Before): effective time iat (Issued At): issued-at time jti (JWT ID): identifier - Signature: a signature over the first two parts to prevent data tampering.
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
- The client includes the JWT when requesting the server.
- The server obtains user data from the JWT instead of querying the database for user data.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub