This is the 11th day of my participation in the August More Text Challenge
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.
Json Web Token. This Token is used as a Web application Token in Json format. Access is authorized by this Token when multiple parties interact with each other. Messages can also be encrypted to prevent them from being tampered with.
Why use it
Traditional Session authentication
After the authentication succeeds, the user information is stored in the Session of the server and the sessionID is stored in the cookie of the browser.
When the user makes a request again, it will carry the cookie and find its session information in the server through the sessionID. To verify login.
The disadvantages of the Session
-
Each authentication user stores the corresponding session on the server. As the number of users increases, the server overhead increases
-
Sessions are stored on one server, and the next request must be made to the same server to succeed, which limits the ability of distribution and weakens load balancing
-
Cookies are intercepted, which is easy to cause forged cookie attacks
-
It is more complicated when the front and back ends are separated:
- Users need to forward multiple requests with sessionID and authentication each time, which increases the burden of the server
Based on the JWT
The certification process
1. The front-end sends its user name and password to the back-end interface through a Web form. Generally, post request or SSL encrypted transmission is used
2. After the user name and password are verified successfully, the backend identifies the user ID as the JWT Payload, combines the user ID with the header, and signs the JWT. ** Token format ** : head. Payload. Singurature
3. The back end returns the JWT to the front end as the result of successful login. The front end saves the result in the localStorage in the browser and deletes the JWT when you log out
4. Each request of the front end will put JWT into the Authorization bit of HTTP Header to solve the forgery attack
5. The backend checks whether the JWT is expired, whether the signature is correct, and whether the Token is sent to the backend.
6. If the authentication succeeds, the backend uses the user information in JWT to perform service operations and returns the result
advantages
- Overview: You can use the POST parameter or HTTP header to send data with a small amount of data and high transmission speed
- Self-contained: The load contains all the information required by users, avoiding multiple database queries
- JWT is stored on the client side in JSON-encrypted form, so JWT is cross-language and any Web form is supported
- There is no need to save session information on the server, especially for distributed micro services
structure
1. Token composition
Token format: XXXX.YYYY.. zzzz
Content is: the header. The payload. Singnature
-
The header header
-
The header usually consists of two parts: the type of token and the signature algorithm used
-
When encoded in Base64, it becomes XXXX, the first part of the JWT format
{// Use HS256" alg" : "HS256", // use JWT" typ" : "JWT"}Copy the code
-
-
Payload
- Self-contained, contain declaration. Declarations are declarations about entities (usually users) and other data
- It is also encoded in Bse64 and becomes the second part of JWT format YYYY
-
Because Base64 is not encryption, but encoding, so if intercepted, it can be decoded to obtain the full user information, and the official advice is not to place sensitive user information such as passwords
{ "sub" : "123456", "name" : "yzy", "admin" : true } Copy the code
-
Singature signature
-
The signature requires the encoded header, payload and a key provided by the back end. The signature uses the encryption algorithm specified by the header to ensure that the JWT is not tampered with
- The header specifies the encryption algorithm: HS256
- The encoded header and payload: XXXX.YYYY are known
- The back-end provides the secret key
- Signatrue = HMACSHA256(XXXX +”.”+ YYYY,secret)
-
How to verify: get XXXX.YYYY in JWT and encrypt it with the back end’s own key and compare it with ZZZZ in JWT
- When the JWT is tampered with, no matter which part of XXXX, YYYY, ZZZZ is changed, the verification will not pass
-
Before encoding
After the coding
use
1. Import dependencies
<dependency> <groupId>com.auth0</groupId> <artifactId> Java -jwt</artifactId> <version>3.4.0</version> </dependency>Copy the code
2. Manually simulate the generation of a token
Calendar instance = Calendar.getInstance(); instance.add(Calendar.SECOND,20); String token = jwt.create ().withclaim ("username", "yy") // Sets the content of the payload. .withclaim ("id", "yy").withexpiresat (instance.getTime()) // Specify token expiration time.sign (algorithm.hMAC256 ("1231231")); // Set the signature system.out.println (token);Copy the code
3. Token authentication
JWTVerifier verifier = JWT.require(Algorithm.HMAC256("1231231")).build(); DecodedJWT verify; DecodedJWT verify; DecodedJWT verify; DecodedJWT verify; DecodedJWT verify =verifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6Inl5MSIsImV4cCI6MTU5OTk3OTM4OCwidXNlcm5hbWUiOiJ5eSJ9.iQnJ 4JnwEGWDEPYzrk-f_Rq8LCqPetm7kYYeAdoUweY"); AsString system.out.println (verify.getClaim("username")); System.out.println(verify.getClaim("id"));Copy the code
abnormal
Order of exceptions:
- 1. Algorithm matching (different from the algorithm generating JWT)
- 2. Validate the signature (different from the signature generated by JWT)
- 3. Expiration Time (timeout)
- 4. Invalid JWT (incorrect JWT information)