一:简介
- token 值: 登录令牌.利用 token 值来判断用户的登录状态.类似于 MD5 加密之后的长字符串
用户登录成功之后,在后端(服务器端)会根据用户信息生成一个唯一的值.这个值就是 token 值
生成完之后将token值返回给前端,前端存储cookie或session中,每次请求接口需要携带token值,后端会进行相应判断,如果过期或者当前值不相同则进行拦截
二:编码
- MD5加密
public static String getMD5Str(String str) {
byte[] digest = null;
try {
MessageDigest md5 = MessageDigest.getInstance("md5");
digest = md5.digest(str.getBytes("utf-8"));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String md5Str = new BigInteger(1, digest).toString(16);
return md5Str;
}
- 生成token
public static <T> String encode(T object,long maxTime){
try{
final JWTSigner signer=new JWTSigner(SECRET);
final Map<String ,Object> data=new HashMap<>(10);
data.put(PAYLOAD,object);
data.put(EXP,System.currentTimeMillis()+maxTime);
return signer.sign(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
- 解密token
public static ReturnBase decode(String jwt) throws Exception{
ReturnBase returnData = new ReturnBase(StatusCode.Success);
final JWTVerifier jwtVerifier=new JWTVerifier(SECRET);
final Map<String,Object> data=jwtVerifier.verify(jwt);
if(data.containsKey(EXP)&&data.containsKey(PAYLOAD)){
long exp = (long) data.get(EXP);
long currentTimeMillis = System.currentTimeMillis();
if(exp > currentTimeMillis){
Map<String,Object> json= (Map<String, Object>) data.get(PAYLOAD);
returnData.setData(json);
}else {
returnData = new ReturnBase(99999,"用户登录超时");
}
}else {
returnData = new ReturnBase(99999,"用户token错误");
}
return returnData;
}