导入maven 依赖
<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.11.0</version>
</dependency>
package org.jeecg.modules.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class TokenUtil {
private static final long EXPIRE_DATE=30*60*100000;
private static final String TOKEN_SECRET = "ZCEQIUBFKSJBFJH2020BQWE";
public static String createJWT(String username,String password) {
if(username == null || password == null){
username ="游客";
password="123456";
}
String token = "";
try {
Date date = new Date(System.currentTimeMillis()+EXPIRE_DATE);
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
Map<String,Object> header = new HashMap<>();
header.put("typ","JWT");
header.put("alg","HS256");
token = JWT.create()
.withHeader(header)
.withClaim("username",username)
.withClaim("password",password).withExpiresAt(date)
.sign(algorithm);
}catch (Exception e){
e.printStackTrace();
return null;
}
return token;
}
public static boolean verify(String token){
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
}