package com.landray.kmss.cmex.ssooauth.util; import io.jsonwebtoken.Claims; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.apache.commons.lang.StringUtils; import java.util.Calendar; import java.util.Date; public class TokenUtil { //过期时间:秒 public static final int EXPIRE = 10; public static String getToken(String appKey, String secretKey) { if (StringUtils.isEmpty(secretKey)) { return null; } Calendar nowTime = Calendar.getInstance(); nowTime.add(Calendar.SECOND, EXPIRE); //过期时间 Date expireDate = nowTime.getTime(); return Jwts.builder() .setHeaderParam("alg", "HS256") .setHeaderParam("typ", "JWT") .setIssuedAt(new Date()) .setIssuer(appKey) .setExpiration(expireDate) .signWith(SignatureAlgorithm.HS256, secretKey) .compact(); } /** * 解析 jwt */ public static boolean verifyToken(String token, String secretKey) { boolean validation = false; Claims claims; try { claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody(); System.out.println("claims--->" + claims); validation = true; } catch (ExpiredJwtException e) { //此异常为生成的token过期异常 System.out.println("token 已过期" + e.getClaims()); e.printStackTrace(); } catch (Exception e) { System.out.println(" Some other exception in JWT parsing !"); e.printStackTrace(); } return validation; } public static void main(String[] args) { String token = getToken("biBoard", "secret"); System.out.println(token); String token1 = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2ODM2MTk4OTcsImlzcyI6ImJpQm9hcmQiLCJleHAiOjE2ODM2MTk5MDZ9.ZHw3LDlPtxtNXS5cM0LHyjyXqspde1BzDwNaVvT_s1k"; boolean validation = verifyToken(token1, "secret"); System.out.println(validation); } }
标签:String,JWT,System,生成,secretKey,token,println,import From: https://www.cnblogs.com/crushgirl/p/17385522.html