客户端用户登录生成token,然后返回给客户端后被存储,然后需要使用时客户端会发送到服务器进行验证。
package com.example.springblog;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import org.junit.jupiter.api.Test;
import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JWTUtisTest {
//过期时间:1小时
private final static long EXPIRATION_DATE = 60*60*1000;
// secretString放的是一个已经生成的key
private final static String secretString ="y46vEE2Bv/LhfkRpqwKDxAGsTKT2p/IfOmplUfA89YE=";
private final static Key key=Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));
//生成令牌
@Test
public void genToken(){
// Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode("y46vEE2Bv/LhfkRpqwKDxAGsTKT2p/IfOmplUfA89YE="));
Map<String,Object> claim = new HashMap<>();
claim.put("id",5);
claim.put("name","zhnagsan");
String token = Jwts.builder()
.setClaims(claim)
.setExpiration(new Date(System.currentTimeMillis()+EXPIRATION_DATE))
.signWith(key)
.compact();
System.out.println(token);
}
//创建Key
@Test
public void genKey(){
//生成key
SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
//解析key
String encode = Encoders.BASE64.encode(secretKey.getEncoded());
System.out.println(encode);
}
//效验令牌
@Test
public void parseToken(){
String token ="eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhuYWdzYW4iLCJpZCI6NSwiZXhwIjoxNzE3MTQ4MDMxfQ.9v9ttOmA8TVrLJyDMIUhq4s4KaitkkMtwcgrmH7jzoM";
JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
Claims body = build.parseClaimsJws(token).getBody();
System.out.println(body);
}
}
需要在pom.xml中引用依赖
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-api --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.5</version> </dependency> <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-impl --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.5</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred --> <version>0.11.5</version> <scope>runtime</scope> </dependency>