package TestToken; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; public class TokenTest { // public key client will not know public static String SECRET="FreeMaNong"; public static String createToken() throws UnsupportedEncodingException { //Signature release time Date iatDate=new Date(); System.out.println(iatDate);//English time //Set the signature expiration time to 1 minute Calendar nowTime=Calendar.getInstance(); nowTime.add(Calendar.MINUTE,1); Date expiresDate=nowTime.getTime(); //System.out.println(expiresDate); Map<String,Object> map=new HashMap<String, Object>(); map.put("alg","HS256");//Set the algorithm to HS256 map.put("typ","JWT");//Set the type to JWT String token=JWT.create().withHeader(map) .withClaim("name","Free码农") .withClaim("age","28") .withClaim("org","Today's headlines") .withClaim("username","chenyu") .withIssuedAt(iatDate)//Set the issue time .withExpiresAt(expiresDate)//Set the expiration time of the past time to be greater than the issuance time .sign(Algorithm.HMAC256(SECRET));//Encrypt with public key //System.out.println(token); return token; } public static Map<String,Claim> verifyToken(String token) throws UnsupportedEncodingException { JWTVerifier verifier =JWT.require(Algorithm.HMAC256(SECRET)).build();//Decrypt and verify with public key DecodedJWT jwt=null; try{ jwt=verifier.verify(token); }catch (Exception e) { throw new RuntimeException("Login credentials have passed, please log in again"); } return jwt.getClaims(); } @Test public void TestToken() throws UnsupportedEncodingException { String token=createToken(); System.out.println("Token:"+token); Map<String,Claim> claims=verifyToken(token); System.out.println(claims.get("name").asString()); System.out.println(claims.get("age").asString()); System.out.println(claims.get("username").asString()); System.out.println(claims.get("org")==null?null:claims.get("org").asString()); //Test expired token // String GuoQiToken="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.izVguZPRsBQ5Rqw6dhMvcIwy8_9lQnrO3vpxGwPCuzs"; // Map<String,Claim> claims2=verifyToken(GuoQiToken); } @Test public void Test() throws UnsupportedEncodingException { Algorithm algorithm = Algorithm.HMAC256("secret"); String token = JWT.create().withIssuer("auth0") .sign(algorithm); System.out.println(token); } }