import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import lombok.experimental.UtilityClass;
import org.slf4j.Logger;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import static org.slf4j.LoggerFactory.getLogger;
/**
* 安全工具
*
* @author JHL
* @version 1.0
* @date 2023/5/15 15:25
* @since : JDK 11
*/
@UtilityClass
public class SecurityUtil {
private static final Logger logger = getLogger(SecurityUtil.class);
private static final byte[] SECRET = "!@#$%^&*(dasdasdsadsa#$%^&*(".getBytes();
/**
* 一天
*/
private static final Integer TIME_OUT = 1440;
/**
* 验证字段头
*/
private static final String VERIFY_KEY = "_a";
public static final String HEADER_AUTH_KEY = "Authorization";
/**
* 系统白名单
*/
public static final String[] WHITELIST_KEY =
new String[]{
"login","code"
};
/**
* 白名单路径跳过验证
*/
public static boolean whitelist(String target) {
for (String s : WHITELIST_KEY) {
if (target.contains(s)) {
return true;
}
}
return false;
}
/**
* token解码
*/
public static JSONObject getPayload(String token) {
return JWTUtil.parseToken(token).getPayloads();
}
/**
* token验证
*/
public static boolean verify(String token) {
boolean r = JWTUtil.verify(token, SECRET);
if (r) {
JSONObject payload = getPayload(token);
if (StrUtil.isNotEmpty(payload.getStr(VERIFY_KEY))) {
DateTime now = DateUtil.date();
DateTime a = DateUtil.date(payload.getLong(VERIFY_KEY));
if (a.after(now)) {
return true;
}
}
}
logger.error("######################### \t[ 登录token过期 ]\t #########################");
return false;
}
/**
* 创建token
*/
public static String createToken(Map<String, Object> payload) {
DateTime now = DateUtil.date();
DateTime a = DateUtil.offset(now, DateField.MINUTE, TIME_OUT);
payload.put("_a", a.getTime());
JWTSigner signer = JWTSignerUtil.hs256(SECRET);
return JWTUtil.createToken(payload, signer);
}
/**
* 在响应头中创建token
*/
public static void createToken(JSONObject payload, HttpServletResponse response) {
response.setHeader(HEADER_AUTH_KEY, createToken(payload));
}
}
标签:String,验证,JWT,public,token,static,import,工具,payload
From: https://www.cnblogs.com/hhddd-1024/p/17436604.html