Generate and verify jwt in java

    In this article, I mainly record how to use java code to generate jwt token in Java, mainly use jjwt to generate and verify jwt , what is JWT, and what JWT can do is not explained in detail.

    The format of jwt: base64(header) . base64(payload) . encryption algorithm (base64(header)+" . "+base64(payload),"private key")

Using JWT in Java

 

1. Introduce the jar package of jjwt

 

<dependency>
      <groupId>io.jsonwebtoken</groupId>
      <artifactId>jjwt</artifactId>
      <version>0.9.0</version>
</dependency>

 

 

 2. Generate JWT token

 

// private key
	private static final String SECRET_KEY = "this is a secret key";

	public static void main(String[] args) {
		// generate token
		String jwtToken = Jwts.builder()
				// header
				.setHeaderParam("typ", "JWT")

				// Declaration in jwt annotation
				.setIssuedAt(new Date()) // Issue time
				.setExpiration(new Date(new Date().getTime() + 10000L))// expiration time
				.setSubject("19930311")// jwt-oriented customers
				.setIssuer("huan")// issuer of jwt

				// public and private declarations
				.claim("user_id", "admin")
				.claim("phone", "18251421000")
				.claim("age", 25)
				.claim("sex", "男")

				// visa
				.signWith(SignatureAlgorithm.HS256, SECRET_KEY.getBytes())

				.compact();

		System.out.println("The generated jwt token is as follows:" + jwtToken);
	}

 

 

3. Verify jwt token

 

// verify jwt
		Jws<Claims> claimsJws = Jwts.parser()
				// Verify that the issuer field iss must be huan
				.require("iss", "huan")
				// set the private key
				.setSigningKey(SECRET_KEY.getBytes())
				// Parse the jwt string
				.parseClaimsJws(jwtToken);

		// get header information
		JwsHeader header = claimsJws.getHeader();
		// get payload information
		Claims payload = claimsJws.getBody();

		System.out.println("The header of the parsed jwt is as follows:" + header.toString());
		System.out.println("The parsed payload of jwt is as follows:" + payload.toString());

 The value of the jwtToken above is the value of the jwt token generated in the second step

 

 Note : 1. .require ("iss","haun") means that the value of the iss field in jwt must be huan

        2. The key for verifying jwt and the key for generating jwt must be the same.

 

4. Results

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326220730&siteId=291194637