119. Basic contents of JWT

Posted by 00Sven on Wed, 02 Feb 2022 08:30:34 +0100

1, Basic concepts of JWT

Official website address: https://jwt.io/

 

1. What is JWT

JWT: JSON WEB TOKEN (a kind of token)

As a token in the web application in the form of JSON, it is used to safely propagate information between parties as JSON objects. In the process of data transmission, it can also complete data encryption, signature and other related processing

 

2. What can JWT do

(1) Authorization

This is the most common scheme using JWT. Once the user logs in, each subsequent request will include JWT, allowing the user to access the routes, services and resources allowed by the token.

Single sign on is a widely used function of JWT at present, because it has low overhead and can be easily used in different domains.

(2) Information exchange

JWT is a good way to securely transfer information between parties. Because JWT can be signed, it can ensure that the sender is the person they say.

In addition, since the signature is calculated using headers and payloads, it can also verify whether the content has been tampered with.

 

2, Traditional session authentication

1. Certification process

http itself is a stateless protocol, which means that if users provide user name and password for user authentication like our application, they have to authenticate again next time. Because http doesn't know which user made the request.

Therefore, we need to store a user login information in the server session. This login information will be passed to the browser when responding, and then the browser will store the information in the cookie and bring the information in the cookie next time.

 

2. Certification demo

Write controller code:

Test:

We did receive a cookie with a sessionId:

 

3. Disadvantages of traditional session authentication

  1. After application authentication, each user should make a record on the server. Generally speaking, the session is saved in memory. With the increase of authenticated users, the memory overhead will increase
  2. After the distributed application is deployed, the memory stored on server A for the first time and server B for the second time may be used. It is troublesome to synchronize the session of the server
  3. The front end is based on cookie s, which may be hijacked and unsafe
  4. Now many websites also block cookie s

 

3, JWT process

1. Process

(1) The front end logs in with the account name and password, and the back end generates jwt (a string of json) and returns to the front end. The front end saves it locally (avoiding the problem that the session occupies memory resources)

(2) The front end carries jwt to access the back end every time (jwt is placed in the request header to prevent cross site scripting attacks). Back end validation jwt

 

2. Advantages

  1. Through url, post parameter, or sent in http header, the data is small and the transmission speed is fast
  2. The load contains all the information required by users to avoid multiple queries to the database
  3. Tokens are stored on the client side in json encryption, so jwt is cross language and is supported by any web in principle
  4. There is no need to save session information on the server, which is suitable for distributed

 

4, Structure of JWT

1. Token composition

  1. Header
  2. Payload
  3. Signature

Use "." in the middle of these three paragraphs Separator: header Payload. Signature

 

2.Header

The header usually consists of two parts: the type of token (i.e. JWT) and the signature algorithm used, such as HMAC, SHA256 or RSA. It will use Base64 coding to form the first part of the JWT structure

Note: Base64 is a kind of coding, that is, it can be translated into the original appearance, rather than a secure encryption process

 

3.Payload

The second part of the token is the payload, which contains the declaration. Declarations are declarations about entities (usually users) and other data. Similarly, it will use Base64 to form the second part of the JWT structure

Note: try not to put the password in the Payload. It's OK to put some general information. It may be intercepted and leaked

 

4.Signature

The first two parts are Base64 encoding, and the original data can be obtained by reverse decoding.

The Signature uses the encoded header, payload and a secret key provided by us, and then uses the Signature algorithm (HS256) specified in the header to sign to ensure that the JWT has not been tampered with.

 

Purpose of signature: the last step of signature is actually to sign the header and load content to prevent the content from being tampered with. If someone makes modifications before coding, plus the signature generated by the secret key must be inconsistent with that stored in the server.

 

5. Output results

The output is three base64 url strings separated by dots. These strings can be easily passed in HTML and HTTP environments, which is more compact than xml based SAML.

 

5, The first program of JWT

Based on the above 2.2 session demo, we continue to do:

 

1. Introduce dependency

 <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.4.0</version>
        </dependency>

2. Generate and verify the token

@SpringBootTest
class SpringbootjwtApplicationTests {

	@Test
	void contextLoads() {
		HashMap<String,Object> map = new HashMap<>();

		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.SECOND,2000);

		String token = JWT.create().withHeader(map)//Header
				.withClaim("userId",21)//payload
				.withClaim("username","xupeng")//payload
				.withExpiresAt(calendar.getTime())//Specify token expiration time
				.sign(Algorithm.HMAC256("sdfhkasdf"));//autograph

		System.out.println(token);
	}

	@Test
	public void test(){
		//Create validation object
		JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("sdfhkasdf")).build();

		DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjMzMTE3NTMsInVzZXJJZCI6MjEsInVzZXJuYW1lIjoieHVwZW5nIn0.MV9hSM-SppCh9EL5jBL2-jdv6leBxZUpASkjvqklxnM");

		System.out.println(verify.getClaim("userId").asInt());
		System.out.println(verify.getClaim("username").asString());
		System.out.println(verify.getExpiresAt());
	}

}

 

6, Tool class encapsulation of JWT

 <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.4.0</version>
        </dependency>
package com.xupeng.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * [jwt Tools]
 *
 * @author : [xupeng]
 * @version : [v1.0]
 * @createTime : [2021/6/10 15:28]
 */
public class JwtUtils {

	//Signature, customized
	private static final String SIGN = "xupeng";

	/**
	 * Generate token header payload. sign
	 */
	public static String getToken(Map<String, String> map) {

		Calendar calendar = Calendar.getInstance();

		//Create jwt builder
		JWTCreator.Builder builder = JWT.create();

		//Set the effective time of token, which is 5 minutes by default
		calendar.add(Calendar.MINUTE, 5);

		//payload
		map.forEach((k, v) -> {
			builder.withClaim(k, v);
		});

		//sign
		String token = builder.withExpiresAt(calendar.getTime())//Specify token expiration time
				.sign(Algorithm.HMAC256(SIGN));


		return token;
	}

	/**
	 * Verify the legitimacy of token
	 */
	public static void verify(String token) {
		JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
	}

	/**
	 * Get token information
	 */
	public static DecodedJWT getTokenInfo(String token) {
		DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
		return verify;
	}
}

 

7, Reward request

If this blog is helpful to you, please give me a reward. Thank you~