Created
March 4, 2019 05:49
-
-
Save zhuhai/e74694a60c5a5134d774bc34be0920f9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.zhuhai; | |
import com.auth0.jwt.JWT; | |
import com.auth0.jwt.JWTVerifier; | |
import com.auth0.jwt.algorithms.Algorithm; | |
import com.auth0.jwt.exceptions.JWTCreationException; | |
import com.auth0.jwt.exceptions.JWTVerificationException; | |
import com.auth0.jwt.interfaces.DecodedJWT; | |
import com.auth0.jwt.interfaces.Verification; | |
import java.util.Date; | |
/** | |
* Created with IntelliJ IDEA. | |
* Date: 2019/1/30 | |
* Time: 15:46 | |
* | |
* @author: zhuhai | |
*/ | |
public class JWTUtil { | |
private static final long EXPIRE_TIME = 100000L; | |
private static final String SECRET = "sdjiew235459#@%$#%^$^sfj23ivgj"; | |
/** | |
* 生成token | |
* @param secret | |
* @return | |
*/ | |
public static String sign(String secret) { | |
try { | |
Algorithm algorithm = Algorithm.HMAC256(secret); | |
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); | |
String sign = JWT.create().withClaim("accountId", 1L).withExpiresAt(date).sign(algorithm); | |
return sign; | |
} catch (JWTCreationException e) { | |
e.printStackTrace(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
public static boolean verify(String token, String secret, Long accountId) { | |
try { | |
Algorithm algorithm = Algorithm.HMAC256(secret); | |
Verification verification = JWT.require(algorithm); | |
JWTVerifier verifier = verification.withClaim("accountId", accountId).build(); | |
verifier.verify(token); | |
return true; | |
} catch (IllegalArgumentException e) { | |
e.printStackTrace(); | |
} catch (JWTVerificationException e) { | |
e.printStackTrace(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return false; | |
} | |
public static Long getAccountId(String token) { | |
DecodedJWT decode = JWT.decode(token); | |
Long accountId = decode.getClaim("accountId").asLong(); | |
return accountId; | |
} | |
public static void main(String[] args) { | |
//String token = sign(SECRET); | |
//System.out.println(token); | |
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NDg4NDIzNTAsImFjY291bnRJZCI6Mn0.4wQYs8UZlZXYrVNTZcUuZmgiDb8_vUd2wKz1CVB82Gg"; | |
Long accountId = getAccountId(token); | |
boolean verify = verify(token, SECRET, accountId); | |
System.out.println(verify); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment