jwt令牌的生成
jwt生成
/*
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,"luo9")
.setClaims(claims)
.setExpiration(new Date(System.currentTimeMillis()+3600*1000))
.compact();
System.out.println(jwt);
}
}
jwt的解析
/*
jwt令牌的解析
*/
@Test
public void testParseJwt(){
Claims luo9 = Jwts.parser()
.setSigningKey("luo9")
.parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoidG9tIiwiaWQiOjEsImV4cCI6MTcwNTI5MDEwM30.9so4ji6psjP9y897AELYB0jnl8_ns5zenvqNqoCh5Zo")
.getBody();
System.out.println(luo9);
}
jwt的工具类
package com.itheima.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.Map;
public class JwtUtils {
private static String signKey="luo9";
private static Long expire=43200000L;
public static String generateJwt(Map<String,Object> claims){
String jwt= Jwts.builder()
.addClaims(claims)
.signWith(SignatureAlgorithm.HS256,signKey)
.setClaims(claims)
.setExpiration(new Date(System.currentTimeMillis()+expire))
.compact();
return jwt;
}
public static Claims parseJwt(String jwt){
Claims claims=Jwts.parser()
.setSigningKey(signKey)
.parseClaimsJws(jwt)
.getBody();
return claims;
}
}