1. 在pom.xml中引入依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
2. 使用Jwts的相关方法生成令牌
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@SpringBootTest
class DemoApplicationTests {
/**
* 生成JWT令牌
*/
@Test
public void testGenJwt() {
Map<String, Object> claims = new HashMap<>();
claims.put("id", 1);
claims.put("name", "tom");
String jwt = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, "itheima") // 签名算法
.setClaims(claims) // 自定义内容(载荷)
.setExpiration(new Date(System.currentTimeMillis() + 3600 * 1000)) // 设置令牌有效期为1小时
.compact();
System.out.println(jwt);
}
}
3. 把生成的令牌复制到JWT官网,查看原始数据
4. 基于Java代码解析生成的令牌
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@SpringBootTest
class DemoApplicationTests {
/**
* 生成JWT令牌
*/
@Test
public void testGenJwt() {
Map<String, Object> claims = new HashMap<>();
claims.put("id", 1);
claims.put("name", "tom");
String jwt = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, "itheima") // 签名算法
.setClaims(claims) // 自定义内容(载荷)
.setExpiration(new Date(System.currentTimeMillis() + 3600 * 1000)) // 设置令牌有效期为1小时
.compact();
System.out.println(jwt);
}
/**
* 解析令牌
*/
@Test
public void testParseJwt() {
Claims claims = Jwts.parser()
.setSigningKey("itheima") // 指定签名密钥
// 解析令牌
.parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoidG9tIiwiaWQiOjEsImV4cCI6MTY3MDQ2NzIyNH0.jL02hIWc1fZBjzvFCTtW4ZlSJ424khsobogsq0X2KVc")
.getBody();
System.out.println(claims);
}
}
注意事项:①JWT校验时使用的签名密钥,必须和生成JWT令牌时使用的密钥是配套的。
②如果JWT令牌解析校验时报错,则说明JWT令牌被篡改或失效了,令牌非法。