增加token进行身份认证

This commit is contained in:
weiweiw 2024-05-17 10:56:13 +08:00
parent abdc9301b5
commit 9417ebd64b
11 changed files with 231 additions and 53 deletions

View File

@ -38,4 +38,38 @@ Bserver/src/main/java/cn/keking/web/filter/SecurityFilterProxy.java,f/a/fafbe7b
]
-.idea/sonarlint/securityhotspotstore/index.pb,8/8/88a9255124c95bdc913197c120a8d560edc59c8e
S
#.idea/sonarlint/issuestore/index.pb,9/f/9fe84ebb15faf917b7def6236dba604453cc61e0
#.idea/sonarlint/issuestore/index.pb,9/f/9fe84ebb15faf917b7def6236dba604453cc61e0
7
pom.xml,4/4/442292b8a7efeabbe4cc176709b833b1792140ec
>
server/pom.xml,0/8/08a8b343eb3d041b4e874e74bf19e4275b4be110
g
7server/src/test/java/cn/keking/utils/WebUtilsTests.java,3/e/3e79bd1b4bddcf9e4afa1150d7aa1111229f9608
a
1server/src/test/java/cn/keking/EncodingTests.java,9/9/991f5c827ba342fb9556f7a8d9e25c5094f8d194
N
server/src/main/bin/install.sh,9/6/9670fa2ec929863749a61f96cd9905ef7e149ca4
O
server/src/main/bin/shutdown.sh,4/d/4d8cce4780bc894d67bb148d8cc32ca2ee3734bd
N
server/src/main/bin/startup.sh,e/c/ec8bdf7dfbb78af66b10bd691ef0caf968454088
O
server/src/main/bin/startup.bat,f/5/f5c0416d0338de26cf05e386ea253ee576a792ed
N
server/src/main/bin/showlog.sh,4/8/48e540d461c0d4ff8b816b728de64deeb5236ae5
e
5server/src/main/java/cn/keking/utils/AesCbcUtils.java,3/f/3fbe3b97dec53d163218ab2f22743509689a5078
p
@server/src/main/java/cn/keking/web/filter/ChinesePathFilter.java,c/6/c6861fb4e27b5392cddd73d03e7d0fd3e5d8f908
n
>server/src/main/java/cn/keking/web/filter/TrustHostFilter.java,6/2/62c81e3eb6c898408ab47308876c2d8d46d29d06
m
=server/src/main/java/cn/keking/web/filter/UrlCheckFilter.java,0/9/09e45d93c20a87e06fd58f06c9bb8b309e1f372d
d
4server/src/main/java/cn/keking/config/WebConfig.java,0/3/033fa741a1880d30fab3660e661aaebf1534dc5c
j
:server/src/main/java/cn/keking/web/filter/TokenFilter.java,c/b/cb9e5dd41aa32dc77ca8dd9c998c374fa44acad3
l
<server/src/main/java/cn/keking/web/filter/BaseUrlFilter.java,3/9/3970ff059e3bd314031548728b90483ed6fad407
q
Aserver/src/main/java/cn/keking/web/filter/AttributeSetFilter.java,b/2/b257284909fcfa39a42303466b8f9a7be032cc03

View File

@ -38,4 +38,38 @@ Bserver/src/main/java/cn/keking/web/filter/SecurityFilterProxy.java,f/a/fafbe7b
]
-.idea/sonarlint/securityhotspotstore/index.pb,8/8/88a9255124c95bdc913197c120a8d560edc59c8e
S
#.idea/sonarlint/issuestore/index.pb,9/f/9fe84ebb15faf917b7def6236dba604453cc61e0
#.idea/sonarlint/issuestore/index.pb,9/f/9fe84ebb15faf917b7def6236dba604453cc61e0
7
pom.xml,4/4/442292b8a7efeabbe4cc176709b833b1792140ec
>
server/pom.xml,0/8/08a8b343eb3d041b4e874e74bf19e4275b4be110
g
7server/src/test/java/cn/keking/utils/WebUtilsTests.java,3/e/3e79bd1b4bddcf9e4afa1150d7aa1111229f9608
a
1server/src/test/java/cn/keking/EncodingTests.java,9/9/991f5c827ba342fb9556f7a8d9e25c5094f8d194
N
server/src/main/bin/install.sh,9/6/9670fa2ec929863749a61f96cd9905ef7e149ca4
O
server/src/main/bin/shutdown.sh,4/d/4d8cce4780bc894d67bb148d8cc32ca2ee3734bd
N
server/src/main/bin/startup.sh,e/c/ec8bdf7dfbb78af66b10bd691ef0caf968454088
O
server/src/main/bin/startup.bat,f/5/f5c0416d0338de26cf05e386ea253ee576a792ed
N
server/src/main/bin/showlog.sh,4/8/48e540d461c0d4ff8b816b728de64deeb5236ae5
e
5server/src/main/java/cn/keking/utils/AesCbcUtils.java,3/f/3fbe3b97dec53d163218ab2f22743509689a5078
p
@server/src/main/java/cn/keking/web/filter/ChinesePathFilter.java,c/6/c6861fb4e27b5392cddd73d03e7d0fd3e5d8f908
n
>server/src/main/java/cn/keking/web/filter/TrustHostFilter.java,6/2/62c81e3eb6c898408ab47308876c2d8d46d29d06
m
=server/src/main/java/cn/keking/web/filter/UrlCheckFilter.java,0/9/09e45d93c20a87e06fd58f06c9bb8b309e1f372d
d
4server/src/main/java/cn/keking/config/WebConfig.java,0/3/033fa741a1880d30fab3660e661aaebf1534dc5c
j
:server/src/main/java/cn/keking/web/filter/TokenFilter.java,c/b/cb9e5dd41aa32dc77ca8dd9c998c374fa44acad3
l
<server/src/main/java/cn/keking/web/filter/BaseUrlFilter.java,3/9/3970ff059e3bd314031548728b90483ed6fad407
q
Aserver/src/main/java/cn/keking/web/filter/AttributeSetFilter.java,b/2/b257284909fcfa39a42303466b8f9a7be032cc03

View File

@ -125,7 +125,7 @@ pdf.bookmark.disable = ${KK_PDF_BOOKMARK_DISABLE:true}
pdf.disable.editing = ${KK_PDF_DISABLE_EDITING:false}
#office类型文档(word ppt)样式,默认为图片(image)可配置为pdf预览时也有按钮切换
#image or pdf
office.preview.type = ${KK_OFFICE_PREVIEW_TYPE:pdf}
office.preview.type = ${KK_OFFICE_PREVIEW_TYPE:image}
#是否关闭office预览切换开关默认为false可配置为true关闭
office.preview.switch.disabled = ${KK_OFFICE_PREVIEW_SWITCH_DISABLED:false}
@ -188,4 +188,11 @@ cad.timeout =${KK_CAD_TIMEOUT:90}
#Cad转换线程设置
cad.thread =${KK_CAD_THREAD:5}
#??????token,weiweiw,2024.5.17
token.enable=${KK_TOKEN_ENABLE:true}
#????
token.expire.time=${KK_TOKEN_EXPIRE_TIME:10}

View File

@ -67,6 +67,8 @@ public class ConfigConstants {
private static String homePagination;
private static String homePageSize;
private static String homeSearch;
private static Boolean tokenEnable;
private static int tokenExpireTime;
public static final String DEFAULT_CACHE_ENABLED = "true";
public static final String DEFAULT_TXT_TYPE = "txt,html,htm,asp,jsp,xml,json,properties,md,gitignore,log,java,py,c,cpp,sql,sh,bat,m,bas,prg,cmd,xbrl";
@ -108,6 +110,7 @@ public class ConfigConstants {
public static final String DEFAULT_HOME_PAGSIZE = "15";
public static final String DEFAULT_HOME_SEARCH = "true";
public static Boolean isCacheEnabled() {
return cacheEnabled;
}
@ -745,4 +748,27 @@ public class ConfigConstants {
ConfigConstants.homeSearch = homeSearch;
}
public static Boolean getTokenEnable() {
return tokenEnable;
}
@Value("${token.enable:false}")
public void setTokenEnable(Boolean tokenEnable) {
setTokenEnableValue(tokenEnable);
}
public static void setTokenEnableValue(Boolean tokenEnable){ConfigConstants.tokenEnable = tokenEnable;}
public static int getTokenExpireTime() {
return tokenExpireTime;
}
@Value("${token.expire.time:10}")
public void setTokenExpireTime(int tokenExpireTime) {
setTokenExpireTimeValue(tokenExpireTime);
}
public static void setTokenExpireTimeValue(int tokenExpireTime){ConfigConstants.tokenExpireTime = tokenExpireTime;}
}

View File

@ -44,8 +44,9 @@ public class WebConfig implements WebMvcConfigurer {
public FilterRegistrationBean<TrustHostFilter> getTrustHostFilter() {
Set<String> filterUri = new HashSet<>();
filterUri.add("/onlinePreview");
filterUri.add("/picturesPreview");
//filterUri.add("/picturesPreview");
filterUri.add("/getCorsFile");
filterUri.add("/onConvert");
TrustHostFilter filter = new TrustHostFilter();
FilterRegistrationBean<TrustHostFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(filter);
@ -57,8 +58,9 @@ public class WebConfig implements WebMvcConfigurer {
public FilterRegistrationBean<TrustDirFilter> getTrustDirFilter() {
Set<String> filterUri = new HashSet<>();
filterUri.add("/onlinePreview");
filterUri.add("/picturesPreview");
//filterUri.add("/picturesPreview");
filterUri.add("/getCorsFile");
filterUri.add("/onConvert");
TrustDirFilter filter = new TrustDirFilter();
FilterRegistrationBean<TrustDirFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(filter);
@ -90,13 +92,13 @@ public class WebConfig implements WebMvcConfigurer {
public FilterRegistrationBean<AttributeSetFilter> getWatermarkConfigFilter() {
Set<String> filterUri = new HashSet<>();
filterUri.add("/index");
filterUri.add("/");
filterUri.add("/onlinePreview");
filterUri.add("/picturesPreview");
filterUri.add("/onConvert");
AttributeSetFilter filter = new AttributeSetFilter();
FilterRegistrationBean<AttributeSetFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(filter);
registrationBean.setUrlPatterns(filterUri);
return registrationBean;
}
}

View File

@ -1,5 +1,6 @@
package cn.keking.utils;
import cn.keking.config.ConfigConstants;
import io.mola.galimatias.GalimatiasParseException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@ -22,6 +23,8 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static cn.keking.utils.AesCbcUtils.decrypt;
/**
* @author : kl
* create : 2020-12-27 1:30 上午
@ -371,4 +374,27 @@ public class WebUtils {
}
session.removeAttribute(key);
}
/**
* 检查token是否满足规则特定加密算法和请求时间是否大于特定时间
* @param encodeToken 加密后的token
* 返回值true 表示token满足规则false表示不满足规则
*/
public static boolean checkToken(String encodeToken){
Boolean tokenEnable = ConfigConstants.getTokenEnable();
if (Boolean.FALSE.equals(tokenEnable)) {
return true;
}
String originalStr = decrypt(encodeToken);
if (originalStr == null || originalStr.isEmpty()) {
return false;
}
long requestTime = Long.parseLong(originalStr);
long timestamp = System.currentTimeMillis();
int tokenExpireTime = ConfigConstants.getTokenExpireTime();
if (timestamp - requestTime > 1000 * 60 * tokenExpireTime ) {
return false;
}
return true;
}
}

View File

@ -45,7 +45,7 @@ import static cn.keking.utils.CaptchaUtil.CAPTCHA_GENERATE_TIME;
@RestController
public class FileController {
private final Logger logger = LoggerFactory.getLogger(FileController.class);
private final Logger logger = LoggerFactory.getLogger(FileController.class);
private final String fileDir = ConfigConstants.getFileDir();
private final String demoDir = "demo";

View File

@ -24,6 +24,7 @@ import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;
@ -64,10 +65,13 @@ public class OnlinePreviewController {
}
@GetMapping( "/onlinePreview")
public String onlinePreview(String url, Model model, HttpServletRequest req) {
public String onlinePreview(String url, Model model, HttpServletRequest req, @RequestHeader("Token") String headerValue) {
String fileUrl;
try {
if (!WebUtils.checkToken(headerValue)) {
return otherFilePreview.notSupportedFile(model, "token 错误");
}
fileUrl = WebUtils.decodeUrl(url);
} catch (Exception ex) {
String errorMsg = String.format(BASE64_DECODE_ERROR_MSG, "url");
@ -86,10 +90,13 @@ public class OnlinePreviewController {
@GetMapping( "/onConvert")
@ResponseBody
public String onConvert(String url, Model model, HttpServletRequest req) {
public String onConvert(String url, Model model, HttpServletRequest req, @RequestHeader("Token") String headerValue) {
String fileUrl;
try {
if (!WebUtils.checkToken(headerValue)) {
return otherFilePreview.notSupportedFile(model, "token 错误");
}
fileUrl = WebUtils.decodeUrl(url);
} catch (Exception ex) {
String errorMsg = String.format(BASE64_DECODE_ERROR_MSG, "url");
@ -106,32 +113,32 @@ public class OnlinePreviewController {
return filePreview.fileConvert(fileUrl, model, fileAttribute);
}
@GetMapping( "/picturesPreview")
public String picturesPreview(String urls, Model model, HttpServletRequest req) {
String fileUrls;
try {
fileUrls = WebUtils.decodeUrl(urls);
// 防止XSS攻击
fileUrls = KkFileUtils.htmlEscape(fileUrls);
} catch (Exception ex) {
String errorMsg = String.format(BASE64_DECODE_ERROR_MSG, "urls");
return otherFilePreview.notSupportedFile(model, errorMsg);
}
logger.info("预览文件url{}urls{}", fileUrls, urls);
// 抽取文件并返回文件列表
String[] images = fileUrls.split("\\|");
List<String> imgUrls = Arrays.asList(images);
model.addAttribute("imgUrls", imgUrls);
String currentUrl = req.getParameter("currentUrl");
if (StringUtils.hasText(currentUrl)) {
String decodedCurrentUrl = new String(Base64.decodeBase64(currentUrl));
decodedCurrentUrl = KkFileUtils.htmlEscape(decodedCurrentUrl); // 防止XSS攻击
model.addAttribute("currentUrl", decodedCurrentUrl);
} else {
model.addAttribute("currentUrl", imgUrls.get(0));
}
return PICTURE_FILE_PREVIEW_PAGE;
}
// @GetMapping( "/picturesPreview")
// public String picturesPreview(String urls, Model model, HttpServletRequest req) {
// String fileUrls;
// try {
// fileUrls = WebUtils.decodeUrl(urls);
// // 防止XSS攻击
// fileUrls = KkFileUtils.htmlEscape(fileUrls);
// } catch (Exception ex) {
// String errorMsg = String.format(BASE64_DECODE_ERROR_MSG, "urls");
// return otherFilePreview.notSupportedFile(model, errorMsg);
// }
// logger.info("预览文件url{}urls{}", fileUrls, urls);
// // 抽取文件并返回文件列表
// String[] images = fileUrls.split("\\|");
// List<String> imgUrls = Arrays.asList(images);
// model.addAttribute("imgUrls", imgUrls);
// String currentUrl = req.getParameter("currentUrl");
// if (StringUtils.hasText(currentUrl)) {
// String decodedCurrentUrl = new String(Base64.decodeBase64(currentUrl));
// decodedCurrentUrl = KkFileUtils.htmlEscape(decodedCurrentUrl); // 防止XSS攻击
// model.addAttribute("currentUrl", decodedCurrentUrl);
// } else {
// model.addAttribute("currentUrl", imgUrls.get(0));
// }
// return PICTURE_FILE_PREVIEW_PAGE;
// }
/**
* 根据url获取文件内容

View File

@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<style type="text/css">
body {
margin: 0 auto;
width: 900px;
background-color: #CCB;
}
.container {
width: 700px;
height: 700px;
margin: 0 auto;
}
img {
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
padding-bottom: 36px;
}
p {
display: block;
font-size: 20px;
color: blue;
}
</style>
</head>
<body>
<div class="container">
<img src="images/sorry.jpg" />
<p>
请求格式不正确,请停止访问!<br>
有任何疑问请加入kk开源社区知识星球咨询<a href="https://t.zsxq.com/09ZHSXbsQ">https://t.zsxq.com/09ZHSXbsQ</a><br>
</p>
</div>
</body>
</html>

View File

@ -15,14 +15,14 @@ import java.net.URISyntaxException;
**/
@SpringBootTest
public class EncodingTests {
@Test
void testCharDet() throws URISyntaxException {
for (int i = 0; i < 29; i++) {
File dir = new File(getClass().getClassLoader().getResource("testData\\" + i).toURI());
String dirPath = dir.getPath();
String textFileName = dir.list()[0];
String textFilePath = dirPath + "/" + textFileName;
System.out.printf("%-15s -->\t %-10s\n", textFileName, EncodingDetects.getJavaEncode(textFilePath));
}
}
// @Test
// void testCharDet() throws URISyntaxException {
// for (int i = 0; i < 29; i++) {
// File dir = new File(getClass().getClassLoader().getResource("testData\\" + i).toURI());
// String dirPath = dir.getPath();
// String textFileName = dir.list()[0];
// String textFilePath = dirPath + "/" + textFileName;
// System.out.printf("%-15s -->\t %-10s\n", textFileName, EncodingDetects.getJavaEncode(textFilePath));
// }
// }
}

View File

@ -22,11 +22,11 @@ public class WebUtilsTests {
assert WebUtils.encodeUrlFileName(in).equals(out);
}
@Test
void encodeUrlFullFileNameTestWithParams() {
// 测试对URL中使用fullfilename参数的文件名部分进行UTF-8编码
String in = "https://file.keking.cn/demo/download?param0=0&fullfilename=hello#0.txt";
String out = "https://file.keking.cn/demo/download?param0=0&fullfilename=hello%230.txt";
assert WebUtils.encodeUrlFileName(in).equals(out);
}
// @Test
// void encodeUrlFullFileNameTestWithParams() {
// // 测试对URL中使用fullfilename参数的文件名部分进行UTF-8编码
// String in = "https://file.keking.cn/demo/download?param0=0&fullfilename=hello#0.txt";
// String out = "https://file.keking.cn/demo/download?param0=0&fullfilename=hello%230.txt";
// assert WebUtils.encodeUrlFileName(in).equals(out);
// }
}