jwt 文档地址:https://github.com/auth0/java-jwt
pom.xml配置:
<dependencies>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.2.0</version>
</dependency>
</dependencies>
密匙:
private static final byte[] SECRET="eyJhbGciPPBMiTKIckGciE0hm3orcuYdaceyJhbGciOiJI904467df11fff26d".getBytes();
jwt 的签发:
public static String creatToken(){
String token = "";
Algorithm algorithm = Algorithm.HMAC256(SECRET);
System.out.println(algorithm.getName());
Map<String,Object> headerClaims = new HashMap<>();
headerClaims.put("typ", "JWT");//声明类型
headerClaims.put("alg", "HS256");//声明加密的算法
Date date = new Date();//当期时间
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date ExpiresDate = null;
try {
ExpiresDate = dateFormat.parse("2018-05-04 12:34:23");
} catch (ParseException e) {
e.printStackTrace();
}
token = JWT.create()
.withHeader(headerClaims)//头部
.withIssuer("auth0dfdsfdsf")//jwt签发者
.withIssuedAt(date)//jwt的签发时间
.withExpiresAt(ExpiresDate)//jwt的过期时间,这个过期时间必须要大于签发时间
.withJWTId("321321321321")//jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击
// .withSubject("sfdf")//jwt所面向的用户
.sign(algorithm);
System.out.println(token);
return token;
}
jwt 验证:
public static void vaildToken(String token){
Algorithm algorithm = Algorithm.HMAC256(SECRET);
DecodedJWT decodedJWT = JWT.decode(token);
String Id = decodedJWT.getId();
String Issuer = decodedJWT.getIssuer();
String Payload = decodedJWT.getPayload();
String Signature = decodedJWT.getSignature();
String Subject = decodedJWT.getSubject();
System.out.println("=======Id=========="+Id);
System.out.println("=======Issuer=========="+Issuer);
System.out.println("=======Payload=========="+Payload);
System.out.println("======Signature=========="+Signature);
System.out.println("======Subject==========="+Subject);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer(Issuer)
.withJWTId(Id)
.withSubject(Subject)
.build();
try{
DecodedJWT jwt = verifier.verify(token);
}catch(TokenExpiredException e){
System.out.println("+-=======时间过期==========");
e.printStackTrace();
}catch(InvalidClaimException e){
System.out.println("+-==========用户id验证失败=======");
e.printStackTrace();
}catch(Exception e){
System.out.println("+-==========验证失败=======");
e.printStackTrace();
}
}
测试:
public static void main(String[] args) {
String token = creatToken();
vaildToken(token);
}