1.引入依赖
<properties>
<jwt.version>0.7.0</jwt.version>
</properties>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jwt.version}</version>
</dependency>
2.Jwt包装工具
package com.atguigu.yygh.common.helper;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;
import java.util.Date;
public class JwtHelper {
private static Long tokenExpiration=24*60*60*1000L;
private static String tokenSignKey="123456";
public static String createToken(long userId,String userName){
String token= Jwts.builder()
.setSubject("yygh-subject")
.claim("userId",userId)
.claim("userName",userName)
.signWith(SignatureAlgorithm.HS256,tokenSignKey)
.setExpiration(new Date(System.currentTimeMillis()+tokenExpiration))
.compressWith(CompressionCodecs.GZIP)
.compact();
return token;
}
public static Long getUserId(String token) {
if(StringUtils.isEmpty(token)){
return null;
}
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
Claims claims = claimsJws.getBody();
Integer userId = (Integer)claims.get("userId");
return userId.longValue();
}
public static String getUserName(String token) {
if(StringUtils.isEmpty(token)){
return "";
}
Jws<Claims> claimsJws
= Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
Claims claims = claimsJws.getBody();
return (String)claims.get("userName");
}
public static void main(String[] args) {
String token = createToken(1001, "张三");
Long userId = getUserId(token);
String userName = getUserName(token);
System.out.println(token+"----"+userId+"-----"+userName);
}
}