parent
5798c47346
commit
386ba7e42c
@ -0,0 +1,55 @@
|
||||
package com.mashibing.internalcommon.util;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.JWTCreator;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class JwtUtils {
|
||||
|
||||
// 盐:服务端本地私有
|
||||
private static final String SIGN = "CPFmsb%!@SSAE";
|
||||
|
||||
// 提供 公共获取 token字符串
|
||||
public static String gerneratorToken(Map<String,String> map){
|
||||
|
||||
// 准备 token过期时间 Date 类型
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.add(Calendar.DATE,1);
|
||||
Date date = calendar.getTime();
|
||||
|
||||
// 使用 JWT 创建 token合成对象 builder
|
||||
JWTCreator.Builder builder = JWT.create();
|
||||
|
||||
// 将 map 中有效数据部份 遍历合成到 builder中
|
||||
if(map == null && map.size() <= 0){// 有效数据为空,直接返回空值
|
||||
return null;
|
||||
}
|
||||
map.forEach(
|
||||
(k,v)-> {
|
||||
builder.withClaim(k,v);
|
||||
}
|
||||
);
|
||||
// 设置 超时时间
|
||||
builder.withExpiresAt(date);
|
||||
|
||||
// 使用 builder对象的 sign 方法生成 token
|
||||
String sign = builder.sign(Algorithm.HMAC256(SIGN));
|
||||
|
||||
return sign;
|
||||
}
|
||||
|
||||
|
||||
public static void main (String [ ] args ) {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("name", "zhang san");
|
||||
map.put("age", "18");
|
||||
String s = gerneratorToken(map);
|
||||
System.out.println("生成的token:" + s);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in new issue