This article introduces the use of JJWT (Java JWT) library to generate JWT Token, the steps are as follows:
- Add dependencies:
Add JJWT dependencies to the project. For Maven projects, the following dependencies can be added to the pom.xml file:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
- Create JWT Token:
The following is a sample code for creating a JWT Token using the JJWT library:
@Test
public void genJwtToken() {
Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
String jwtToken = Jwts.builder().setSubject("JWT Demo") // 设置主题(Subject)
.claim("userId", "oscar").claim("role", "admin").signWith(key) // 使用指定的算法和密钥签名
.compact();
System.out.println("jwtToken="+jwtToken);
}
In the above example, the following information is set:
- The subject (Subject) is "JWT Demo"
- The custom claim (Claim)
usessignWith()
the method to specify the signature algorithm (HS256 is used here) and key for "userId" and "oscar". Finally, usecompact()
the method to generate a JWT Token.
The generated Token is shown in the figure below:
- Adjust Token validity period (optional):
By default, the generated JWT Token has no expiration time. If you need to set the validity period of the Token, you can usesetExpiration()
the method to specify the validity period, the example is as follows:
@Test
public void tokenWithExpired() {
Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000); // 设置过期时间为1小时后
String jwtToken = Jwts.builder().setSubject("JWT Demo") // 设置主题(Subject)
.setExpiration(expiration) //设置过期时间
.claim("userId", "oscar").claim("role", "admin")
.signWith(key) // 使用指定的算法和密钥签名
.compact();
System.out.println("jwtToken="+jwtToken);
}
In the above example, use setExpiration()
the method to set the expiration time of the Token to 1 hour after the current time.