<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @Auther: 张瑛
* @Date: 2022/8/3 0003 22:03
* @ClassName: TokenUtil
* @Version: 1.0
* @Description:
*/
public class TokenUtil {
//设置过期时间
private static final long EXPIRE_DATE = 10000; //10秒
//token秘钥
private static final String TOKEN_SECRET = "ZCEQIUBFKSJBFJH2020BQWE";
public static String token(String username, String password, Long i) {
String token = "";
try {
//过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE * i);
//秘钥及加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
//设置头部信息
Map<String, Object> header = new HashMap<>();
header.put("typ", "JWT");
header.put("alg", "HS256");
//携带username,password信息,生成签名
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 (TokenExpiredException e) {
return false;
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) throws InterruptedException {
String username = "zhangsan";
String password = "123";
String token = token(username, password, 1L);
String token2 = token(username, password, 2L);
for (int i = 0; i < 50; i++) {
System.out.println("***********************************");
System.out.println(i + " : " + verify(token));
System.out.println(i + " : " + verify(token2));
System.out.println("***********************************");
Thread.sleep(1000);
}
}
}