jwt数据结构参考https://jwt.io/introduction/
引用的jar包:
asm-1.0-RC1.jar
commons-codec-1.8.jar
cors-filter-2.2.1.jar
java-property-utils-1.9.1.jar
javax.mail.jar
json-smart-2.0-RC2.jar
nimbus-jose-jwt-4.13.1.jar
package com.jwt;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.Payload;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import net.minidev.json.JSONObject;
public class Jwt {
/**
* 秘钥
*/
private static final byte[] SECRET = "xxxxxxxxxxxxxxxxxxxxxxx".getBytes();
/**
* 初始化head部分数据
*/
private static final JWSHeader header = new JWSHeader(JWSAlgorithm.HS256, JOSEObjectType.JWT, null, null, null,
null, null, null, null, null, null, null, null);
/**
* 生成token 在用户登录成功之后 传入json token第二部分的数据 以map的形式 Map集合,可以存储用户id,token生成时间,token过期时间等自定义字段
*/
public static String createToken(Map<String, Object> payload) {
String tokenString = null;
/**
* 创建一个jwsObject
*/
JWSObject jwsObject = new JWSObject(header, new Payload(new JSONObject(payload)));
try {
jwsObject.sign(new MACSigner(SECRET));// 加密
tokenString = jwsObject.serialize();
} catch (JOSEException e) {
// TODO Auto-generated catch block
System.err.println("签名失败...." + e.getMessage());
}
return tokenString;
}
/**
* 校验token
*/
public static Map<String, Object> validToken(String token) {
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
JWSObject jwsObject = JWSObject.parse(token);
// JWSHeader header2 = jwsObject.getHeader();
Payload payload = jwsObject.getPayload();
// Base64URL signature = jwsObject.getSignature();
JWSVerifier verifier = new MACVerifier(SECRET);
if (jwsObject.verify(verifier)) {// 验证
JSONObject jsonOBj = payload.toJSONObject();
// token校验成功(此时没有校验是否过期)
resultMap.put("state", TokenCode.VALID.toString());
if (jsonOBj.containsKey("expired")) { // 如果包含expired 字符则为过期
long extTime = Long.valueOf(jsonOBj.get("expired").toString());
long curTime = new Date().getTime();
/* 过期了 */
if (curTime > extTime) {
resultMap.clear();
resultMap.put("state", TokenCode.EXPIRED.toString());
}
}
resultMap.put("data", jsonOBj);
} else {
// 校验失败
resultMap.put("state", TokenCode.INVALID.toString());
}
} catch (Exception e) {
// TODO Auto-generated catch block
resultMap.clear();
resultMap.put("state", TokenCode.INVALID.toString());
}
return resultMap;
}
}