<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
工具类:
import com.example.online_class.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
/**
* JWT工具类
*/
public class JwtUtils {
/**
* 有效时间
*/
private static final long EXPIRE = 60000 * 60 * 24 * 7;
/**
* 加密密钥
*/
private static final String SECRET = "xxx";
/**
* 令牌前缀
*/
private static final String TOKEN_PREFIX = "xxx";
/**
* subject
*/
private static final String SUBJECT = "xxx";
/**
* 根据用户信息,生成令牌
* @param user
* @return
*/
public static String geneJsonWebToken(User user){
String token = Jwts.builder().setSubject(SUBJECT)
.claim("name",user.getName())
.claim("id",user.getId())
.claim("head_img",user.getHeadImg())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
.signWith(SignatureAlgorithm.ES256,SECRET)
.compact();
token = TOKEN_PREFIX + token;
return token;
}
/**
* 校验token的方法
*/
public static Claims checkJWT(String token){
try {
Claims claims = Jwts.parser().setSigningKey(SECRET)
.parseClaimsJws(token.replace(TOKEN_PREFIX,""))
.getBody();
return claims;
}catch (Exception e){
return null;
}
}
}