相關jar包下載:
鏈接:https://pan.baidu.com/s/1Bdd2cJubPPdKxJUDCbdM4w
提取碼:xlvm
commons-codec-1.11.jar jar包盡量用高版本的,低版本會報錯org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString,最低版本是哪個沒有進行測試。
jwt工具類:
import java.util.Date; import java.util.HashMap; import java.util.Map; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; public class JwtUtil { //過期時間 private static final long EXPIRE_TIME = 15 * 60 * 1000; //私鑰 private static final String TOKEN_SECRET = "privateKey"; /** * 生成簽名,15分鍾過期 * @param **username** * @param **password** * @return */ public static String sign(Long userId) { try { // 設置過期時間 Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); // 私鑰和加密算法 Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); // 設置頭部信息 Map<String, Object> header = new HashMap<>(2); header.put("Type", "Jwt"); header.put("alg", "HS256"); // 返回token字符串 return JWT.create() .withHeader(header) .withClaim("userId", userId) .withExpiresAt(date) .sign(algorithm); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 檢驗token是否正確 * @param **token** * @return */ public static Long verify(String token){ try { Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); JWTVerifier verifier = JWT.require(algorithm).build(); DecodedJWT jwt = verifier.verify(token); Long userId = jwt.getClaim("userId").asLong(); return userId; } catch (Exception e){ return 0L; } } }