Cabbage Java self study room covers core knowledge
1. What is JWT
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact, self-contained way to securely transfer information between parties as JSON objects. This information can be authenticated and trusted because it is digitally signed.
JWT is designed to be compact and secure, especially suitable for single sign-on (SSO) scenarios in distributed sites. The JWT declaration is generally used to pass authenticated user identity information between the identity provider and the service provider to obtain resources from the resource server, and to add some additional declaration information necessary for other business logic. The token can also be used directly for authentication or can be encrypted.
1.1. Traditional Session authentication
Speaking of JWT, we should talk about the difference between token-based authentication and traditional session authentication.
As we know, the HTTP protocol itself is a stateless protocol, which means that if the user to our application provides a user name and password for user authentication, so the next time a request, the user will once again for user authentication, because based on HTTP protocol, we don’t know is which user requests, So in order for our application to be able to identify which user is making the request, we can only store a copy of the user’s login information on the server, and this login information is passed to the browser in response, telling it to save as a cookie, so that it can be sent to our application in the next request. So our application can identify the user from whom the request is coming, which is traditional session-based authentication.
However, session-based authentication makes it difficult to expand the application itself. With the increase of different client users, the independent server can no longer bear more users, and the problems of session-based authentication applications will be exposed.
Problems with session-based authentication
- Session: After each user is authenticated by our application, our application makes a record on the server to facilitate the identification of the user’s next request. Generally speaking, sessions are stored in memory. However, as the number of authenticated users increases, the overhead on the server will increase significantly.
- Scalability: After the user is authenticated, the server makes authentication records. If the authentication records are stored in memory, it means that the user’s next request must be made on this server to obtain authorized resources, which limits the capacity of the load balancer in distributed applications. This also means limiting the application’s ability to scale.
- CSRF: Because user identification is based on cookies, if cookies are intercepted, users will be vulnerable to cross-site request forgery.
1.2. Token-based authentication mechanism
Similar to HTTP, token-based authentication is stateless and does not need to retain user authentication information or session information on the server. This means that token-based applications do not need to consider which server users log in to, which facilitates application expansion.
The process looks like this:
- The user requests the server using a username and password
- The server authenticates the user’s information
- The server sends the user a token through authentication
- The client stores the token and supplies it with each request
- The server validates the token value and returns data
This token must be passed to the server on every request. It should be stored in the header of the request. Additionally, the server must support the CORS(Cross-source resource sharing) policy.
2. What does JWT look like
JWT is made up of three pieces of information. Use these three pieces of information text. The links together make up the Jwt string. Something like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cB ab30RMHrHDcEfxjoYZgeFONFh7HgQCopy the code
3. Composition of JWT
The first part we call the header, the second part we call the payload, and the third part is the signature.
3.1. The header
The header of the JWT carries two pieces of information:
- The declaration type in this case is JWT
- Algorithms that declare encryption usually use HMAC SHA256 directly
The complete header looks like this JSON:
{
'typ': 'JWT',
'alg': 'HS256'
}
Copy the code
Base64 encryption of the header, which can be decrypted symmetrically, then forms the first part.
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
Copy the code
3.2. playload
The payload is where the useful information is stored. The name seems to refer specifically to the cargo carried on the plane, and this valid information consists of three parts:
- A declaration of registration in a standard
- Public statement
- Private declaration
Declarations registered in the standard (recommended but not mandatory) :
- Iss: JWT issuer
- Sub: The user JWT is targeting
- Aud: The side receiving the JWT
- Exp: indicates the expiration time of the JWT. The expiration time must be greater than the issue time
- NBF: Define before what time the JWT is unavailable
- Iat: issue time of JWT
- Jti: Unique IDENTIFIER of the JWT. It is used as a one-time token to avoid replay attacks
A public statement:
Public declarations can add any information, usually about the user or other information necessary for the business. However, it is not recommended to add sensitive information because this part can be decrypted on the client side.
Private declaration:
Private declarations are defined by both providers and consumers. Sensitive information is generally not recommended because Base64 is symmetrically decrypted, meaning that part of the information can be classified as plaintext information.
Define a payload:
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
Copy the code
It is then base64 encrypted to get the second part of the JWT.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9
Copy the code
3.3. signature
The third part of the JWT is a visa information, which consists of three parts:
- Header (Base64)
- Payload (base64)
- secret
This part is used by the base64-encrypted header and the Base64-encrypted payload. A string of concatenated strings, then salted secret with the encryption method declared in the header, which forms the third part of the JWT.
String encodedString = base64UrlEncode(header) + '.' + base64UrlEncode(payload);
String signature = HMACSHA256(encodedString, 'secret'); // TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
Copy the code
These three parts are concatenated into a complete string to form the final JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cB ab30RMHrHDcEfxjoYZgeFONFh7HgQCopy the code
Note: Secret is stored on the server side, JWT generation is also on the server side, secret is used for JWT signing and JWT authentication, so it is your server side private key and should not be disclosed in any scenario. Once the client is aware of this Secret, it means that the client can issue the JWT itself.
4. How is JWT applied
In general, the Authorization has been added to the header of the request and the Bearer has been labeled:
headers: {
'Authorization': 'Bearer ' + token
}
Copy the code
The server validates the token and returns the corresponding resource if it succeeds. Here’s how it works:
5. Advantages and disadvantages of JWT
5.1. JWT advantages
- Json’s generality. As a result, JWT can be cross language support, like JAVA, JavaScript, NodeJS, many languages such as PHP can be used;
- Because of the payload part, JWT can store non-sensitive information in itself that is necessary for other business logic.
- Easy to transport. JWT is very simple in structure and has a small byte footprint, so it is very easy to transport;
- It does not need to store session information on the server, so it is easy to apply extensions.
5.2. JWT shortcomings
- Sensitive information should not be stored in the Payload part of the JWT because it is the part that the client can decrypt.
- Protect the secret private key, which is very important.
- If yes, use HTTPS.