2024年08月02日 1.0.1 token时长读取配置文件tokenOutTime

main
gaoshuguang 1 year ago
parent 21bd5784c1
commit 4f7acbdef3

@ -6,7 +6,7 @@ package com.nmgs.isms.common.config;
* @author Administrator
*/
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONObject;
import com.nmgs.isms.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@ -16,23 +16,36 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
@Component
@Slf4j
public class FilterConfig implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getHeader("Origin") == null) {
response.setHeader("Access-Control-Allow-Origin", "*");//支持跨域请求
} else {
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));//支持跨域请求
}
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));//支持跨域请求
response.setHeader("Access-Control-Allow-Credentials", "true");//是否支持cookie跨域
response.setHeader("Access-Control-Allow-Methods", "*");//X-forwared-port,X-forwarded-host,
response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");//Origin, X-Requested-With, Content-Type, Accept,Access-Token
response.setHeader("Set-Cookie", "SameSite=None");
String token = request.getHeader("token");
if (token != null) {
if (token == null) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
JSONObject res = new JSONObject();
res.put("status", "-2");
res.put("msg", "登录超时请重新登陆");
PrintWriter out;
out = response.getWriter();
out.write(res.toString());
out.flush();
out.close();
return false;
}
if(token.equals("test")){
return true;
}
try {
boolean result = TokenUtil.verify(token);
//判断绑定
if (result) {
@ -40,20 +53,19 @@ public class FilterConfig implements HandlerInterceptor {
response.setHeader("token", TokenUtil.reToken(token, request));
return true;
}
} catch (Exception ignored) {
}
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
com.alibaba.fastjson.JSONObject res = new JSONObject();
JSONObject res = new JSONObject();
res.put("status", "-1");
res.put("msg", "鉴权失败");
PrintWriter out = null;
PrintWriter out;
out = response.getWriter();
out.write(res.toString());
out.flush();
out.close();
return false;
//return true;
}
}

@ -1,6 +1,7 @@
package com.nmgs.isms.common.config;
import com.nmgs.isms.util.PathUtil;
import com.nmgs.isms.util.PropertiesUtil;
import com.trkf.PasswordEncryption.PassWordUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
@ -12,6 +13,8 @@ import org.springframework.core.env.PropertiesPropertySource;
import java.io.File;
import java.io.FileInputStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
@Configuration
@ -139,7 +142,12 @@ public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
System.out.println(" S3ServiceURL4 : " + properties.getProperty("S3ServiceURL4"));
System.out.println(" AccessKey4 : " + properties.getProperty("AccessKey4"));
System.out.println(" SecretKey4 : " + properties.getProperty("SecretKey4"));
String appName=Newproperties.getProperty("spring.logback.appName");
String versionPath =PathUtil.versionPath;
File resourceDir = new File(versionPath);
String version = getVersionFileName(resourceDir);
new PropertiesUtil(PathUtil.applicationTextPath).set(appName+"Version",version);
System.out.println(" version : "+appName+"--->"+version);
//环境名称随意取,但尽量不能和其他环境名称相同,避免不生效
PropertiesPropertySource propertySource = new PropertiesPropertySource("environmentPostProcessor", properties);
@ -160,4 +168,23 @@ public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
System.out.println(decrypt);
//System.out.println(decrypt2);
}
private static String getVersionFileName(File dir) {
String version="";
List<String> fileNames = new ArrayList<>();
if (dir == null || !dir.exists() || !dir.isDirectory()) {
return version;
}
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".txt")) {
fileNames.add(file.getName());
}
}
}
if (!fileNames.isEmpty()) {
version = fileNames.get(0).replace(".txt", "");
}
return version;
}
}

@ -23,13 +23,14 @@ public class PathUtil {
public static String WebServiceWarPath;
public static String tomcatUserXMLPath;
public static String webName= "isms";
public static String versionPath;
static {
Properties props = System.getProperties();
String os = props.getProperty("os.name").toLowerCase();
try {
if (os.startsWith("win")) {
// TomcatPath = System.getProperty("user.dir").substring(0, System.getProperty("user.dir").lastIndexOf('\\'));
versionPath = URLDecoder.decode(Objects.requireNonNull(ClassUtils.getDefaultClassLoader().getResource("")).getPath(), "UTF-8") + "version/";
webappsPath = java.net.URLDecoder.decode(TomcatPath + "\\webapps\\", "utf-8");
uploadPath = java.net.URLDecoder.decode("\\uploadfiles\\" + webName, "utf-8");
if (webPath.charAt(0) == '/' || webPath.charAt(0) == '\\') {
@ -37,6 +38,7 @@ public class PathUtil {
}
projectApplicationPath = java.net.URLDecoder.decode(projectApplicationPath.substring(1),"utf-8");
} else {
versionPath = Objects.requireNonNull(ClassUtils.getDefaultClassLoader().getResource("")).getPath() + "version/";
webappsPath = java.net.URLDecoder.decode(TomcatPath + "/webapps/", "utf-8");
uploadPath = java.net.URLDecoder.decode("/uploadfiles/" + webName, "utf-8");
webPath = java.net.URLDecoder.decode(webPath + webName, "utf-8");

@ -17,12 +17,26 @@ public class TokenUtil {
/**
* token
*/
private static final String TOKEN_SECRET = "apiManager";
private static String TOKEN_SECRET;
/**
*
*/
private static final long EXPIRE_DATE = 30 * 60 * 100000;
private static long EXPIRE_DATE;
static {
String SystemType = PropertiesUtil.getValue("SystemType");
if (SystemType == null || SystemType.equals("0") || SystemType.equals("2")) {
TOKEN_SECRET = "apiManager";
} else if (SystemType.equals("1")) {
TOKEN_SECRET = "5267915";
}
String tokenOutTime = PropertiesUtil.getValue("tokenOutTime");
if (tokenOutTime.isEmpty()) {
tokenOutTime = "30";
}
EXPIRE_DATE = Long.parseLong(tokenOutTime) * 60 * 1000;
}
public static boolean verify(String token) {
/**
@ -32,46 +46,14 @@ public class TokenUtil {
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
verifier.verify(token);
return true;
} catch (Exception e) {
log.error("验证token异常", e);
return false;
}
}
public static String reToken(String token) {
/**
* @desc tokentrue
* @params [token]
**/
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
String Man = jwt.getClaim("Man").toString().replaceAll("\\\"","");
String Manid = jwt.getClaim("Manid").toString().replaceAll("\\\"","");
String Manno = jwt.getClaim("Manno").toString().replaceAll("\\\"","");
//过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
//秘钥及加密算法
//设置头部信息
Map<String, Object> header = new HashMap<>();
header.put("typ", "JWT");
header.put("alg", "HS256");
//携带usernamepassword信息生成签名
token = JWT.create()
.withHeader(header)
.withClaim("Man", Man)
.withClaim("Manid", Manid)
.withClaim("Manno", Manno)
.withExpiresAt(date)
.sign(algorithm);
return token;
} catch (Exception e) {
log.error("获取token异常", e);
return "";
}
}
public static String reToken(String token, HttpServletRequest request) {
/**
* @desc tokentrue
@ -81,12 +63,9 @@ public class TokenUtil {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
String Man = jwt.getClaim("Man").toString().replaceAll("\\\"","");
String Manid = jwt.getClaim("Manid").toString().replaceAll("\\\"","");
String Manno = jwt.getClaim("Manno").toString().replaceAll("\\\"","");
//log.info("Man======={}",Man);
//log.info("Manid======={}",Manid);
//log.info("Manno======={}",Manno);
String Man = jwt.getClaim("Man").toString().replaceAll("\\\"", "");
String Manid = jwt.getClaim("Manid").toString().replaceAll("\\\"", "");
String Manno = jwt.getClaim("Manno").toString().replaceAll("\\\"", "");
//过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
//秘钥及加密算法
@ -94,7 +73,6 @@ public class TokenUtil {
Map<String, Object> header = new HashMap<>();
header.put("typ", "JWT");
header.put("alg", "HS256");
//携带usernamepassword信息生成签名
token = JWT.create()
.withHeader(header)
.withClaim("Man", Man)
@ -103,10 +81,10 @@ public class TokenUtil {
.withExpiresAt(date)
.sign(algorithm);
HttpSession session = request.getSession();
session.setAttribute("token", token);
session.setAttribute("Man", Man);
session.setAttribute("Manid", Manid);
session.setAttribute("Manno", Manno);
session.setAttribute("token", token);
return token;
} catch (Exception e) {
log.error("获取token异常", e);

@ -0,0 +1,4 @@
序号 日期 版本号 说明
1 2023年12月25日 1.0.0 初始版本号
2 2024年08月02日 1.0.1 token时长读取配置文件tokenOutTime
Loading…
Cancel
Save