Compare commits

..

155 Commits

Author SHA1 Message Date
56da1a23c2 更新issue格式要求 2024-06-21 17:08:37 +08:00
d3c5a58db9 更新README 2024-06-21 15:19:53 +08:00
d44945f688 提示语修改 2024-06-20 19:34:15 +08:00
f370855683 还原方法模式的脱敏注解 2024-06-20 18:35:34 +08:00
c582efd115 Merge pull request #6339 from EightMonth/master
还原原有数据脱敏功能并新增@sensitive脱敏注解,不依赖原有数据脱敏功能
2024-06-20 18:11:55 +08:00
c687c7a916 修改注解名称 2024-06-20 18:03:06 +08:00
8e44080b00 还原原有数据脱敏功能并新增@Sensitive脱敏注解,不依赖原有数据脱敏功能 2024-06-20 17:57:36 +08:00
56ca53cc93 Merge pull request #6332 from EightMonth/master
优化数据脱敏功能
2024-06-20 16:10:02 +08:00
0075ec6751 更新README 2024-06-19 18:06:56 +08:00
7e31341f1a 更新readme 2024-06-19 18:03:42 +08:00
d4ca2eb934 项目地址修改 2024-06-19 17:15:20 +08:00
84946888ad 更新readme 2024-06-19 15:49:49 +08:00
d276c3d8ad 更新readme 2024-06-19 15:25:48 +08:00
7dccaf2ec8 优化数据脱敏功能 2024-06-19 12:25:34 +08:00
ae1b8d4654 优化数据脱敏功能 2024-06-19 11:15:33 +08:00
49f709a32a 升级积木报表到最新版1.7.6 2024-06-19 11:03:31 +08:00
335c369546 提示语修改 2024-06-19 10:02:33 +08:00
1a446007c7 解决租户角色保存问题 ,多租户模式下,【租户角色】新增角色后,列表中看不到新增记录 2024-06-19 10:02:22 +08:00
76f9575140 3.7.0 大版本发布(更新数据库) 2024-06-18 23:13:43 +08:00
fd7783644f Merge pull request #6329 from EightMonth/master
修复字典导出问题,修复 #6311
2024-06-18 22:43:06 +08:00
f6a3e11aa2 修复字典导出问题,修复 #6311 2024-06-18 17:34:42 +08:00
c2768cea85 解决[数据表jimu_report_data_source,字段connect_times的类型问题 #6316] 2024-06-18 16:27:37 +08:00
2d37b166a2 解决:分配权限必须退出重新登录才生效,造成很多用户困扰 2024-06-18 16:18:35 +08:00
cff5ec5a40 解决:分配权限必须退出重新登录才生效,造成很多用户困扰(目前改法缺陷:只针对当前登录人的权限修改生效) 2024-06-18 16:04:45 +08:00
0947a199b6 补充遗漏的权限配置 2024-06-18 16:03:44 +08:00
2ecfe74b33 补充遗留的权限配置 2024-06-18 12:03:14 +08:00
6147e923de 3.7.0 大版本发布(调整增量sql,如果大家报错手工执行并改下表flyway_schema_history的状态) 2024-06-18 11:58:06 +08:00
3a07d5a983 分配权限需要退出重新登录,给明确提示 2024-06-18 11:34:43 +08:00
2747868ea7 3.7.0 大版本发布(优化代码生成器模板) 2024-06-17 17:50:59 +08:00
dcc27d71b4 1 2024-06-17 16:33:19 +08:00
30c0482b6d 遗漏升级sql 2024-06-17 16:33:06 +08:00
641298b32d 补充积木报表缺少的升级sql 2024-06-17 16:31:02 +08:00
09a536f549 3.7.0 大版本发布 2024-06-17 09:24:00 +08:00
35ab818741 3.7.0 大版本发布 2024-06-15 17:33:32 +08:00
e00358859c 3.7.0 大版本发布(chatgpt依赖放到底层) 2024-06-13 16:20:35 +08:00
aa24978d2b 3.7.0 大版本发布 2024-06-13 15:06:40 +08:00
ee497a8d1e 3.7.0 大版本发布(代码生成器模板大升级) 2024-06-13 14:30:24 +08:00
935575576f 3.7.0 大版本发布 2024-06-13 14:01:37 +08:00
b45e75007b 3.7.0 大版本发布 2024-06-13 11:43:50 +08:00
52ae0c359e 3.7.0 大版本发布(补充online所需接口权限) 2024-06-13 10:51:46 +08:00
06e6594b75 3.7.0 大版本发布(升级online) 2024-06-13 10:16:01 +08:00
73d62b484c 3.7.0 大版本发布(仪表盘模块升级) 2024-06-12 18:49:38 +08:00
0ff93a220d 3.7.0 大版本发布(仪表盘模块升级) 2024-06-12 18:49:24 +08:00
2071b5bcc4 3.7.0 大版本发布 2024-06-12 16:38:38 +08:00
e1378f4ee5 3.7.0 大版本发布 2024-06-12 14:45:37 +08:00
a6b6e7c9d4 3.7.0大版本发布 2024-06-11 22:58:04 +08:00
857fb53fa1 Merge pull request #6293 from EightMonth/master
优化生产环境屏蔽swagger处理
2024-06-06 10:42:17 +08:00
9db6c1a7ac 优化生产环境屏蔽swagger处理 2024-06-06 10:39:50 +08:00
fd0461644e 免token注解@IgnoreAuth改造后, 不需此代码 2024-06-05 19:05:16 +08:00
10263720d4 Merge pull request #6220 from EightMonth/master
修复#6100、#6169、@IgnoreAuth扫描加速
2024-06-05 18:18:23 +08:00
7548f3aa60 Merge pull request #6114 from EightMonth/master
rocketmq-starter应用举例
2024-05-13 10:59:08 +08:00
ad3d2eb3fc 修复#6169 2024-04-30 13:49:34 +08:00
d0406fcd83 发issue,请明确那个分支 2024-04-28 15:49:35 +08:00
9159b55096 发issue,请明确那个分支 2024-04-26 15:07:50 +08:00
faebdee755 修复#6100、@IgnoreAuth扫描加速 2024-04-25 11:52:41 +08:00
2fc672dfab 写错了 2024-04-22 09:35:01 +08:00
4dc4e87900 解决SQL注入检测逻辑影响业务 #6105 2024-04-20 18:34:52 +08:00
13d00a8bb4 【issues/6113】online表单生成代码, 关联表生成vue3模板里的 *.data.ts 这个文件会有报错 2024-04-17 10:43:19 +08:00
fb95cf7f2f -- 修复设置用户生日格式报错 2024-04-17 09:59:48 +08:00
78f048fda5 增加新QQ群⑨808791225 2024-04-15 13:50:00 +08:00
200adb8490 使用代码生成器生成树的结构,批量删除时报错,在很老的jeecg,vue2版本就在报错了 #6043 2024-04-12 15:42:37 +08:00
f1496b5084 rocketmq-starter应用举例 2024-04-12 10:16:30 +08:00
7b06715bff 排除minidao的子依赖jsqlparser和druid,总与mybatisplus冲突 2024-04-11 11:13:39 +08:00
3091d5b6f0 缩小IgnoreAuth注解扫描范围 2024-04-08 15:03:13 +08:00
c117abb2d4 升级druid到1.2.22 2024-04-08 14:23:49 +08:00
dbc3f13c65 补充注释说明 2024-04-08 14:03:27 +08:00
ea6927a2a7 Merge pull request #6007 from EightMonth/master
修复 #5901
2024-04-08 13:52:58 +08:00
b69a716b04 修改druid配置类名称 2024-04-08 13:45:27 +08:00
7e71fa26d7 升级druid v1.2.22版本兼容处理 2024-04-08 13:11:55 +08:00
4fed40ff7d Update pom.xml 2024-04-03 16:06:04 +08:00
ee4ff35c90 Revert "修复 #6070"
This reverts commit 6edef14f07.
2024-04-03 16:04:29 +08:00
c9b92decaf Revert "处理升级druid 1.2.22版本兼容处理"
This reverts commit eed3bc346d.
2024-04-03 16:04:23 +08:00
eed3bc346d 处理升级druid 1.2.22版本兼容处理 2024-04-03 16:01:39 +08:00
6edef14f07 修复 #6070 2024-04-03 11:18:47 +08:00
ab49983759 回滚druid版本升级,导致问题“角色功能报错,列表查询报错。 #6070” 2024-04-03 09:44:01 +08:00
5a09a6fb4a Merge branch 'master' into master 2024-04-02 15:43:35 +08:00
ac93bf7d6b 升级积木报表到1.7.4,升级druid到1.2.22 2024-04-01 13:47:48 +08:00
c9c6dd5c1d Online表单中 下拉搜索框 搜索时报sql错误,生成的SQL多了一个 “and" #5978
字典下拉异步出错 #1108
2024-03-28 14:44:24 +08:00
e3e1cd6b0d 修复 #5936 2024-03-25 16:27:53 +08:00
f3cf90bd28 在租户不隔离的情况下导出部门报错 2024-03-25 09:42:33 +08:00
70847d17f1 升级积木报表版本 2024-03-23 21:22:29 +08:00
2cfc39b23f Merge branch 'master' of https://github.com/EightMonth/jeecg-boot 2024-03-22 17:12:32 +08:00
c8676b3040 优化注解生效范围配置 2024-03-22 17:11:18 +08:00
73bd04d04a Merge branch 'master' into master 2024-03-22 16:38:39 +08:00
0ca4badb77 修复 #6021 2024-03-22 16:37:00 +08:00
80b92ca132 flowable、activiti都支持 2024-03-22 16:22:48 +08:00
58865bef28 jimureport-drag:2.0.1 报错 java.lang.IllegalStateException: No TaglibFactory available #6021 2024-03-20 22:59:27 +08:00
9fd40d0973 代码生成器jar包中携带配置文件导致 spring.profiles.active 被覆盖 #6010 2024-03-20 10:07:54 +08:00
266ebd9122 修复 #5901 2024-03-19 09:41:29 +08:00
fee729e16c 【回滚】暂时回退mybatisplus、minidao版本,online模块不兼容 2024-03-18 14:06:09 +08:00
10a3e9c6ba 升级knife4j、mybatisplus、justauth、minidao版本 2024-03-18 10:11:05 +08:00
990f79fdfe 调整flyway配置,检查数据库类型只有mysql才启用 2024-03-18 09:27:54 +08:00
6360aee0ff 【QQYUN-8561】企业微信登陆请求接口设置上下文不一致,导致接口404 2024-03-18 09:25:51 +08:00
685b81e5ec Merge pull request #5930 from EightMonth/master
处理 #5601 ,添加@ignoreAuth注解
2024-03-15 15:30:48 +08:00
e38e395436 Merge branch 'master' into master 2024-03-15 15:29:35 +08:00
39af6e25ee ChatGPT AI助手,对接配置文档 2024-03-11 19:08:33 +08:00
b15e6e0422 【优化代码生成功能】uniapp调整目录 2024-03-09 22:30:41 +08:00
8f99a80352 【优化代码生成功能】uniapp调整目录、升级sql的命名改成flyway规则 2024-03-09 22:11:00 +08:00
936a87e738 积木报表 v1.7.2 紧急发布,修复 1.7.1 严重 Bug 2024-03-07 22:32:39 +08:00
2af165b201 【3.6.3版本发布】初始化sql有问题启动报flyway错误 2024-03-07 11:30:51 +08:00
3d5efc07ad 【3.6.3版本发布】升级积木报表的升级SQL 2024-03-06 19:02:39 +08:00
21e8d640d2 【3.6.3版本发布】升级积木报表的升级SQL 2024-03-06 18:55:35 +08:00
b0ce456909 【3.6.3版本发布】升级积木报表的升级SQL 2024-03-06 18:45:44 +08:00
b8e1306955 【3.6.3版本发布】升级积木报表的升级SQL 2024-03-06 18:44:35 +08:00
37a38ad288 【3.6.3版本发布】升级版本号 2024-03-06 17:13:05 +08:00
9ee05c9510 【3.6.3版本发布】新版数据库脚本 2024-03-06 17:00:54 +08:00
275a68bb6a 忽略文件 2024-03-06 16:24:23 +08:00
f3f70e8549 【3.6.3版本发布】代码修复 2024-03-06 16:22:36 +08:00
e15e9d80c4 【3.6.3版本发布】ai聊天模块新增代码 2024-03-06 16:22:03 +08:00
f7538c1ed8 【3.6.3版本发布】首页支持自定义 2024-03-06 16:20:49 +08:00
a9dba08a8d 【3.6.3版本发布】性能优化部分代码 2024-03-06 16:19:51 +08:00
acf0713385 Update ShiroConfig.java 2024-02-29 17:43:56 +08:00
cee872000a 处理 #5601 ,添加@ignoreAuth注解 2024-02-29 17:11:44 +08:00
4a857680d0 原生表单新增携带 createTime 等系统字段 #1033 2024-02-23 09:59:19 +08:00
a47d0984dc [issues/5755]vue代码不加入逻辑删除字段
[issue/#5711]修复用户选择组件在生成代码后变成部门用户选择组件
[issues/1022]我这个控件是哪里设置没对吗,为什么打开已有的记录,会触发提示“请输入”验证? #1022
fix 带条件字典存在单引号导致js编译错误
2024-02-19 16:40:33 +08:00
e333b126b6 微服务下字典拦截器报错 2024-01-10 14:58:01 +08:00
3618842f44 [issue/5787]增加非空判断防止代码生成时空指针异常 2024-01-09 19:12:16 +08:00
fd8c848c9e 修改小bug 2024-01-07 20:30:49 +08:00
09614a0239 修复几个bug 2024-01-07 20:28:41 +08:00
6fe8f1d81a 从3.6.2+版本增加flyway自动升级数据库机制 2024-01-04 14:56:06 +08:00
0bd7f715c4 默认删除人大金仓依赖,需要请自己放开 2024-01-04 13:57:23 +08:00
041d88161e 2024年首版本发布(antd4和仪表盘大升级) 2024-01-03 22:12:07 +08:00
79a62aa056 从3.6.2+版本增加flyway自动升级数据库机制 2024-01-03 22:07:27 +08:00
b86b4d9676 从3.6.2+版本增加flyway自动升级数据库机制 2024-01-03 22:01:07 +08:00
aeaac80012 2024年首版本发布(antd4和仪表盘大升级) 2024-01-03 19:46:35 +08:00
e0ef20cf08 3.6.2版本对应的数据库脚本 2024-01-03 18:58:30 +08:00
169a66f5dd 升级新版本号3.6.2 2024-01-03 13:47:33 +08:00
7e39b31123 日志暂时不做权限控制 2024-01-03 13:44:36 +08:00
18765450a6 2024年首版本发布(仪表盘大升级) 2024-01-03 13:40:44 +08:00
dff8c84d9c 2024年首版本发布(仪表盘大升级) 2024-01-03 13:37:06 +08:00
d962c34846 新版数据库,有新升级sql和权限授权配置 2024-01-03 13:36:01 +08:00
cd9794d818 删除无用代码 2023-12-31 17:11:18 +08:00
5034b7cf18 提供新版仪表盘 2023-12-31 15:14:04 +08:00
fdde84c68a 代码生成器更新 2023-12-29 21:14:49 +08:00
4c54ff6f52 Merge branch 'master' of https://github.com/zhangdaiscott/jeecg-boot 2023-12-29 19:44:16 +08:00
de3285dc1b 通知公告 2023-12-29 19:43:12 +08:00
7f0c035c4c 企业微信集成改造 2023-12-29 19:42:36 +08:00
43593e8def 加权限注解 2023-12-29 19:42:24 +08:00
48b0b608d8 租户改造 2023-12-29 19:42:13 +08:00
69287a772b 小功能修改 2023-12-29 19:41:44 +08:00
337d5a9489 Merge pull request #5692 from hoperunChen/fix-QQYUN-7527
fix QQYUN-7527 vue3代码生成默认带上高级查询
2023-12-26 14:35:56 +08:00
cfeb81ee1e Merge branch 'master' of https://github.com/zhangdaiscott/jeecg-boot.git 2023-12-26 14:08:37 +08:00
09f92f01aa 提交online新依赖(解决online接口安全漏洞问题) 2023-12-26 14:08:20 +08:00
6d1094936b Merge pull request #5691 from hoperunChen/Fix-QQYUN-7583
fix QQYUN-7583 Vue3风格表单页面多选控件渲染成了下拉多选
2023-12-26 14:00:59 +08:00
8836a2793a Merge pull request #5690 from hoperunChen/fix-issues-#5658
fix issues #5658 树表复选框与展开按钮重叠问题
2023-12-26 13:59:52 +08:00
c36ece8923 补充信息 2023-12-23 19:24:15 +08:00
a82213b90c 还原错误提交 2023-12-21 15:47:28 +08:00
98facdd2ee Merge branch 'master' of https://github.com/zhangdaiscott/jeecg-boot.git 2023-12-21 15:45:21 +08:00
d080b0b5ea SpringBoot3+JDK17版本可以下载了 2023-12-21 15:36:09 +08:00
338902ca0c Merge pull request #5706 from hoperunChen/fix-issue-vue3-#939
fix issue vue3 #939 npm run build 失败
2023-12-21 14:59:56 +08:00
7ae6a11cf0 fix issue vue3 #939: modify file suffix 2023-12-21 14:31:51 +08:00
cdbe1cb1a9 fix issue vue3 #939 2023-12-21 13:31:04 +08:00
090f790df4 fix QQYUN-7527 vue3代码生成,默认带上高级查询 2023-12-19 11:06:05 +08:00
82d051f388 fix QQYUN-7583 Vue3风格表单页面多选控件渲染成了下拉多选 2023-12-19 11:05:16 +08:00
5a3631c332 fix issues #5658 树表复选框与展开按钮重叠问题 2023-12-19 11:03:18 +08:00
529 changed files with 14946 additions and 58341 deletions

View File

@ -1,21 +1,13 @@
##### 版本号:
##### 前端版本vue3版还是 vue2版
##### 问题描述:
##### 截图&代码:
##### 错误截图:
#### 友情提示为了提高issue处理效率
- 未按格式要求发帖,会被直接删掉;
- 描述过于简单或模糊,导致无法处理的,会被直接删掉
- 请自己初判问题描述是否清楚,是否方便我们调查处理;
- 针对问题请说明是Online在线功能(需说明用的主题模板),还是生成的代码功能;
#### 友情提示:
- 未按格式要求发帖、描述过于简抽象的,会被直接删掉
- 请确保问题描述清楚,方便我们理解并一次性调查解决问题
- 如果使用的不是master请说明你使用的那个分支

5
.gitignore vendored
View File

@ -10,5 +10,6 @@ rebel.xml
## front
**/*.lock
os_del.cmd
*.log
os_del_doc.cmd
.svn
derby.log

View File

@ -7,13 +7,13 @@
JEECG BOOT Low Code Development Platform
===============
当前最新版本: 3.6.1发布日期2023-12-11
当前最新版本: 3.7.0发布日期2024-06-17
[![AUR](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg)](https://github.com/zhangdaiscott/jeecg-boot/blob/master/LICENSE)
[![](https://img.shields.io/badge/Author-guojusoft-orange.svg)](http://www.jeecg.com)
[![](https://img.shields.io/badge/Blog-blog-blue.svg)](https://jeecg.blog.csdn.net)
[![](https://img.shields.io/badge/version-3.6.1-brightgreen.svg)](https://github.com/zhangdaiscott/jeecg-boot)
[![](https://img.shields.io/badge/version-3.7.0-brightgreen.svg)](https://github.com/zhangdaiscott/jeecg-boot)
[![GitHub stars](https://img.shields.io/github/stars/zhangdaiscott/jeecg-boot.svg?style=social&label=Stars)](https://github.com/zhangdaiscott/jeecg-boot)
[![GitHub forks](https://img.shields.io/github/forks/zhangdaiscott/jeecg-boot.svg?style=social&label=Fork)](https://github.com/zhangdaiscott/jeecg-boot)
@ -37,19 +37,18 @@ JEECG Business process: Using workflow to implement and extend the task interfac
Technical support
-----------------------------------
Problems or bugs in use can be found in [Making on the Issues](https://github.com/jeecgboot/jeecg-boot/issues/new)
Problems or bugs in use can be found in [Making on the Issues](https://github.com/jeecgboot/JeecgBoot/issues/new)
Official Support: http://jeecg.com/doc/help
Download the source code
-----------------------------------
项目源码
-----------------------------------
| Source |Front-end source (Vue3 version) | The background source |
|-|-|-|
| Github | [jeecgboot-vue3](https://github.com/jeecgboot/jeecgboot-vue3) | [jeecg-boot](https://github.com/jeecgboot/jeecg-boot) |
| Gitee | [jeecgboot-vue3](https://gitee.com/jeecg/jeecgboot-vue3) | [jeecg-boot](https://gitee.com/jeecg/jeecg-boot) |
- UI(Vue3) SourceCodehttps://github.com/jeecgboot/jeecgboot-vue3
- APP SourceCodehttps://github.com/jeecgboot/jeecg-uniapp
##### Project description
@ -58,7 +57,6 @@ Download the source code
| `jeecg-boot` | SpringBoot background source code (support microservices) |
| `jeecgboot-vue3` | Vue3+TS new front-end source code|
| `jeecg-uniapp` | [APP development framework, a code multi terminal adaptation, and support APP, small program, H5](https://github.com/jeecgboot/jeecg-uniapp) |
| `SpringBoot3+JDK17` | [BranchSourceCode](https://github.com/jeecgboot/jeecg-boot/tree/springboot3) [UpgradeBlog](https://blog.csdn.net/zhangdaiscott/article/details/134805602) |
| `More` | [Download more source code](http://jeecg.com/download) |
@ -74,9 +72,9 @@ Docker starts the project
-----------------------------------
- [Docker starts the monomer background](https://help.jeecg.com/java/setup/docker/up.html)
- [Docker starts the Vue3 front-end](http://help.jeecg.com/publish/docker.html)
- [Docker starts the front-end](http://help.jeecg.com/publish/docker.html)
- [Docker starts the micro-service background](https://help.jeecg.com/java/springcloud/docker.html)
- [ChatGPT AI Config](https://help.jeecg.com/java/chatgpt.html)
@ -87,18 +85,11 @@ Technical documentation
- Doc [http://help.jeecg.com](http://help.jeecg.com)
- Newbie guide [Quick start](http://www.jeecg.com/doc/quickstart) | [video](https://space.bilibili.com/454617261/channel/series) | [Q&A ](http://www.jeecg.com/doc/qa) | [help](http://jeecg.com/doc/help) | [1 minute experience](https://my.oschina.net/jeecg/blog/3083313)
- Microservice Development [Monomer upgrade to microservice](https://help.jeecg.com/java/springcloud/switchcloud/monomer.html)
- QQ group ⑧825232878、⑦791696430、⑥730954414(full)、683903138(full)、⑤860162132(full)、④774126647(full)、③816531124(full)、②769925425(full)、①284271917(full)
- Demo [Vue3](http://boot3.jeecg.com) | [Vue2](http://boot.jeecg.com) | [APP](http://jeecg.com/appIndex)
- QQ group ⑨808791225、⑧825232878、⑦791696430、⑥730954414(full)、683903138(full)、⑤860162132(full)、④774126647(full)、③816531124(full)、②769925425(full)、①284271917(full)
- Demo [OnlineDemo](http://boot3.jeecg.com) | [APP](http://jeecg.com/appIndex)
> [please click obtain account password to obtain](http://jeecg.com/doc/demo)
Thinking
-----------------------------------
> We are pursuing the goal of implementing complex business systems without writing code! That has been done so far
- https://www.qiaoqiaoyun.com
Star charts
-----------------------------------
@ -161,7 +152,7 @@ Why JeecgBoot?
* Support SAAS service model and provide SaaS multi-tenant architecture solution.
* Distributed file service, integration of minio, Ali OSS and other excellent third parties, to provide convenient file upload and management, but also support local storage.
* Mainstream database compatibility, a set of code is fully compatible with Mysql, Postgresql, Oracle, Sqlserver, MariaDB, dream and other mainstream databases.
* Integrate workflow activiti and realize only the configuration of flow direction in the page, which can greatly simplify the development of bpm workflow; Using bpm's process designer to draw the flow direction, a workflow is basically complete with a small amount of java code;
* Integrate workflow flowable and realize only the configuration of flow direction in the page, which can greatly simplify the development of bpm workflow; Using bpm's process designer to draw the flow direction, a workflow is basically complete with a small amount of java code;
* Low code ability: online process design, using open source Activiti process engine, to achieve online drawing process, custom form, form attachment, business flow
* Multi-data source: its simple way of use, online configuration of data source configuration, convenient to grab data from other data;
* Provide single sign-on CAS integration solution, and complete docking code has been provided in the project
@ -228,8 +219,7 @@ Technical Architecture:
#### The front end
- Vue2 version`Vue2.6+@vue/cli+AntDesignVue+Viser-vue+Vuex` [detail](https://github.com/jeecgboot/ant-design-vue-jeecg)
- Vue3 version`Vue3.0+TypeScript+Vite+AntDesignVue+pinia+echarts` [detail](https://github.com/jeecgboot/jeecgboot-vue3)
- TechnologyStack`Vue3.0+TypeScript+Vite+AntDesignVue+pinia+echarts`
#### Support library
@ -441,6 +431,10 @@ Technical Architecture:
### Effect of system
##### ChatGPT AI Dialog
> Go to the JeecgBoot background home page and click "AI Assistant" in the middle of the right side of the home page. The AI Assistant dialog screen is displayed.
![](https://oscimg.oschina.net/oscnet/up-7c6405641a40f56638999d52da0cb5b4343.png)
##### PC
![](https://oscimg.oschina.net/oscnet/up-000530d95df337b43089ac77e562494f454.png)

240
README.md
View File

@ -1,19 +1,14 @@
![JEECG](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/logov3.png "JeecgBoot低代码开发平台")
JEECG BOOT 低代码开发平台
JeecgBoot 低代码开发平台
===============
当前最新版本: 3.6.1发布日期2023-12-11
当前最新版本: 3.7.0发布日期2024-06-17
[![AUR](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg)](https://github.com/zhangdaiscott/jeecg-boot/blob/master/LICENSE)
[![](https://img.shields.io/badge/Author-北京国炬软件-orange.svg)](http://jeecg.com/aboutusIndex)
[![](https://img.shields.io/badge/Blog-官方博客-blue.svg)](https://jeecg.blog.csdn.net)
[![](https://img.shields.io/badge/version-3.6.1-brightgreen.svg)](https://github.com/zhangdaiscott/jeecg-boot)
[![](https://img.shields.io/badge/version-3.7.0-brightgreen.svg)](https://github.com/zhangdaiscott/jeecg-boot)
[![GitHub stars](https://img.shields.io/github/stars/zhangdaiscott/jeecg-boot.svg?style=social&label=Stars)](https://github.com/zhangdaiscott/jeecg-boot)
[![GitHub forks](https://img.shields.io/github/forks/zhangdaiscott/jeecg-boot.svg?style=social&label=Fork)](https://github.com/zhangdaiscott/jeecg-boot)
@ -24,122 +19,77 @@ JEECG BOOT 低代码开发平台
<h3 align="center">Java Low Code Platform for Enterprise web applications</h3>
JeecgBoot 是一款基于代码生成器的`低代码开发平台`!前后端分离架构 SpringBoot2.xSpringCloudAnt Design&VueMybatis-plusShiroJWT支持微服务。强大的代码生成器让前后端代码一键生成实现低代码开发! JeecgBoot 引领新的低代码开发模式(OnlineCoding-> 代码生成器-> 手工MERGE) 帮助解决Java项目70%的重复工作,让开发更多关注业务。既能快速提高效率,节省研发成本,同时又不失灵活性!
JeecgBoot 是一款基于代码生成器的`低代码开发平台`!前后端分离架构 SpringBoot2.x和3.xSpringCloudAnt Design&VueMybatis-plusShiroJWT支持微服务。强大的代码生成器让前后端代码一键生成实现低代码开发! JeecgBoot 引领新的低代码开发模式(OnlineCoding-> 代码生成器-> 手工MERGE) 帮助解决Java项目70%的重复工作,让开发更多关注业务。既能快速提高效率,节省研发成本,同时又不失灵活性!
JeecgBoot 提供了一系列`低代码模块`,实现在线开发`真正的零代码`Online表单开发、Online报表、报表配置能力、在线图表设计、大屏设计、移动配置能力、表单设计器、在线设计流程、流程自动化配置、插件能力可插拔等等
JeecgBoot 提供了一系列`低代码模块`,实现在线开发`真正的零代码`Online表单开发、Online报表、报表配置能力、在线图表设计、仪表盘设计、大屏设计、移动配置能力、表单设计器、在线设计流程、流程自动化配置、插件能力(可插拔)等等!
`JEECG宗旨是:` 简单功能由OnlineCoding配置实现做到`零代码开发`复杂功能由代码生成器生成进行手工Merge 实现`低代码开发`,既保证了`智能`又兼顾`灵活`;实现了低代码开发的同时又支持灵活编码,解决了当前低代码产品普遍不灵活的弊端!
`JEECG业务流程:` 采用工作流来实现、扩展出任务接口,供开发编写业务逻辑,表单提供多种解决方案: 表单设计器、online配置表单、编码表单。同时实现了流程与表单的分离设计松耦合、并支持任务节点灵活配置既保证了公司流程的保密性又减少了开发人员的工作量。
遇到技术问题,[请在这里反馈BUG](https://github.com/jeecgboot/jeecg-boot/issues/new)
适用项目
-----------------------------------
Jeecg-Boot低代码开发平台可以应用在任何J2EE项目的开发中尤其适合SAAS项目、企业信息管理系统MIS、内部办公系统OA、企业资源计划系统ERP、客户关系管理系统CRM其半智能手工Merge的开发方式可以显著提高开发效率70%以上,极大降低开发成本。
Jeecg-Boot低代码开发平台可以应用在任何J2EE项目的开发中支持信创国产化(默认适配达梦和人大金仓)。尤其适合SAAS项目、企业信息管理系统MIS、内部办公系统OA、企业资源计划系统ERP、客户关系管理系统CRM其半智能手工Merge的开发方式可以显著提高开发效率70%以上,极大降低开发成本。
项目源码
源码下载
-----------------------------------
| 仓库 |前端源码 Vue3版 | 后端JAVA源码 |
|-|-|-|
| Github | [jeecgboot-vue3](https://github.com/jeecgboot/jeecgboot-vue3) | [jeecg-boot](https://github.com/jeecgboot/jeecg-boot) |
| 码云 | [jeecgboot-vue3](https://gitee.com/jeecg/jeecgboot-vue3) | [jeecg-boot](https://gitee.com/jeecg/jeecg-boot) |
- 前端源码地址https://github.com/jeecgboot/jeecgboot-vue3
- APP源码地址https://github.com/jeecgboot/jeecg-uniapp
#### 项目说明
| 项目名 | 说明 |
|--------------------|------------------------|
| `jeecgboot-vue3` | 端源码 (Vue3版本) |
| `jeecg-boot` | 后端JAVA源码支持微服务 |
| `jeecg-uniapp` | [APP开发框架一份代码多终端适配,同时支持APP、小程序、H5](https://github.com/jeecgboot/jeecg-uniapp) |
| `SpringBoot3+JDK17 后端分支` | [分支源码](https://github.com/jeecgboot/jeecg-boot/tree/springboot3) [升级博客](https://blog.csdn.net/zhangdaiscott/article/details/134805602) |
| `更多开源项目` | [更多底层源码下载](http://jeecg.com/download) |
| `jeecg-boot` | 端源码JAVASpringBoot微服务架构 |
| `jeecgboot-vue3` | 前端源码VUE3vue3+vite5+ts最新技术栈 |
| `jeecg-uniapp` | APP框架,一份代码多终端适配支持APP、小程序、H5 |
快速搭建开发环境
技术支持
-----------------------------------
- [通过IDEA导入项目](https://help.jeecg.com/java/setup/idea.html)
关闭gitee的issue通道使用中遇到问题或者BUG可以在 [Github上提Issues](https://github.com/jeecgboot/JeecgBoot/issues/new)
快速启动项目
-----------------------------------
- [前端项目快速启动](http://help.jeecg.com/setup/startup.html)
- [通过IDEA启动前后端项目](https://help.jeecg.com/java/setup/idea/startup.html)
- [Vue3前端项目快速启动](http://help.jeecg.com/setup/startup.html)
- [单体快速切换为微服务版](https://help.jeecg.com/java/springcloud/switchcloud/monomer.html)
Docker快速启动项目
Docker启动项目
-----------------------------------
- [Docker启动单体后台](https://help.jeecg.com/java/setup/docker/up.html)
- [Docker启动Vue3前端](http://help.jeecg.com/publish/docker.html)
- [Docker启动前端](http://help.jeecg.com/publish/docker.html)
- [Docker启动后台](https://help.jeecg.com/java/setup/docker/up.html)
微服务方式启动
-----------------------------------
- [单体快速切换微服务](https://help.jeecg.com/java/springcloud/switchcloud/monomer.html)
- [Docker启动微服务后台](https://help.jeecg.com/java/springcloud/docker.html)
技术文档
-----------------------------------
- 项目官网: [http://www.jeecg.com](http://www.jeecg.com)
- 开发文档: [http://help.jeecg.com](http://help.jeecg.com)
- 产品官网: [http://www.jeecg.com](http://www.jeecg.com)
- 开发文档: [https://help.jeecg.com](https://help.jeecg.com)
- 新手指南: [快速入门](http://www.jeecg.com/doc/quickstart) | [常见问题 ](http://www.jeecg.com/doc/qa) | [视频教程](https://space.bilibili.com/454617261/channel/series) | [1分钟低代码体验](https://my.oschina.net/jeecg/blog/3083313)
- AI助手配置: https://help.jeecg.com/java/chatgpt.html
- 在线演示 [Vue3演示](http://boot3.jeecg.com) | [APP演示](http://jeecg.com/appIndex) | [敲敲云零代码](https://qiaoqiaoyun.com)
- 在线演示 [在线演示](http://boot3.jeecg.com) | [APP演示](http://jeecg.com/appIndex)
> 演示系统的登录账号密码,请点击 [获取账号密码](http://jeecg.com/doc/demo) 获取
>
- QQ交流群 ⑧825232878、⑦791696430(满)、⑥730954414(满)、683903138(满)、⑤860162132(满)、④774126647(满)、③816531124(满)、②769925425(满)、①284271917(满)
> ` 提醒【QQ群是自助服务群建议给帮助您解决问题的同学发送指定红包表示感谢】 `
大龄码农的思考
-----------------------------------
> 作为码农年纪大了写不动代码了怎么办??哎!!
所以我们团队在追求不写代码也可实现复杂业务系统!目前已经做到了,不信你到敲敲云零代码试试(通过流程串联修改业务数据)
- https://www.qiaoqiaoyun.com
技术支持
-----------------------------------
关闭gitee的issue通道使用中遇到问题或者BUG可以在 [Github上提Issues](https://github.com/jeecgboot/jeecg-boot/issues/new)
官方支持: [http://jeecg.com/doc/help](http://jeecg.com/doc/help)
VUE2版本专题介绍
-----------------------------------
#### 项目介绍
- 项目名称ant-design-vue-jeecg
- 说明JeecgBoot前端提供两套解决方案一套VUE2和一套VUE3版本目前vue2版本最新代码只支持到jeecgboot 3.4.3版本,一定注意。
#### 源码下载
| 源码 | 源码地址 |
|--------------------|------------------------|
| 后端JAVA源码 `Vue2版` |https://gitee.com/jeecg/jeecg-boot/tree/v3.4.3last |
| 前端vue2源码 `Vue2版` |https://gitee.com/jeecg/ant-design-vue-jeecg |
#### Vue2与Vue3版本区别
> - VUE3版本彻底抛弃IE兼容不兼容IE和低版本浏览器只适配高版本谷歌和Edge
政府、事业类单位项目需要谨慎选择——国产化迁移是一个漫长的过程万一过程中要求IE兼容这个不可逆
> - 所以如果对浏览器有要求的项目请选择VUE2版本。
> - VUE3版是全新的技术栈紧跟主流前端重写各个功能都做了优化拥有更好的体验效果
#### 技术文档
- 在线演示:[Vue2版演示](http://boot.jeecg.com)
- 开发文档:| [开发文档](http://doc.jeecg.com) | [Vue2前端快速启动](http://doc.jeecg.com/2678320) | [Vue2前端采用Docker启动](http://doc.jeecg.com/3043612)
Star走势图
-----------------------------------
[![Star History Chart](https://api.star-history.com/svg?repos=jeecgboot/jeecg-boot&type=Date)](https://star-history.com/#jeecgboot/jeecg-boot)
- QQ交流群 ⑨808791225、⑧825232878、⑦791696430(满)、⑥730954414(满)、683903138(满)、⑤860162132(满)、④774126647(满)、③816531124(满)、②769925425(满)、①284271917(满)
@ -196,8 +146,8 @@ Star走势图
* 17.支持SAAS服务模式提供SaaS多租户架构方案。
* 18.分布式文件服务集成minio、阿里OSS等优秀的第三方提供便捷的文件上传与管理同时也支持本地存储。
* 19.主流数据库兼容一套代码完全兼容Mysql、Postgresql、Oracle、Sqlserver、MariaDB、达梦等主流数据库。
* 20.集成工作流activiti、flowable并实现了只需在页面配置流程转向可极大的简化bpm工作流的开发用bpm的流程设计器画出了流程走向一个工作流基本就完成了只需写很少量的java代码
* 21.低代码能力:在线流程设计,采用开源Activiti流程引擎,实现在线画流程,自定义表单,表单挂靠,业务流转
* 20.集成工作流flowable并实现了只需在页面配置流程转向可极大的简化bpm工作流的开发用bpm的流程设计器画出了流程走向一个工作流基本就完成了只需写很少量的java代码
* 21.低代码能力:在线流程设计,采用开源flowable流程引擎,实现在线画流程,自定义表单,表单挂靠,业务流转
* 22.多数据源:及其简易的使用方式,在线配置数据源配置,便捷的从其他数据抓取数据;
* 23.提供单点登录CAS集成方案项目中已经提供完善的对接代码
* 24.低代码能力表单设计器支持用户自定义表单布局支持单表一对多表单、支持select、radio、checkbox、textarea、date、popup、列表、宏等控件
@ -236,7 +186,7 @@ Star走势图
- 缓存Redis
- 数据库脚本MySQL5.7+ & Oracle 11g & Sqlserver2017(其他数据库,[需要自己转](https://my.oschina.net/jeecg/blog/4905722)
- 数据库脚本MySQL5.7+ (其他数据库,[需要自己转](https://my.oschina.net/jeecg/blog/4905722)
#### 后端
@ -262,8 +212,7 @@ Star走势图
#### 前端
- Vue2版本`Vue2.6+@vue/cli+AntDesignVue+Viser-vue+Vuex等` [详细查看](https://github.com/jeecgboot/ant-design-vue-jeecg)
- Vue3版本`Vue3.0+TypeScript+Vite+AntDesignVue+pinia+echarts等新方案` [详细查看](https://github.com/jeecgboot/jeecgboot-vue3)
- 技术栈:`Vue3.0+TypeScript+Vite+AntDesignVue+pinia+echarts等最新技术栈`
#### 支持库
@ -467,17 +416,10 @@ Star走势图
```
### 流程引擎推荐
JeecgBoot企业版本默认集成了activiti和flowable两套方案大家在使用本开源项目时如果想进一步集成流程引擎推荐结合贺波老师的书 [《深入Activiti流程引擎核心原理与高阶实战》](https://item.m.jd.com/product/13928958.html?gx=RnAomTM2bmCImZxDqYAkVCoIHuIYVqc)
<img src="https://jeecgos.oss-cn-beijing.aliyuncs.com/files/tuijian20231220161656.png" width="25%" height="auto">
### 系统效果
##### PC端
![](https://oscimg.oschina.net/oscnet/up-000530d95df337b43089ac77e562494f454.png)
@ -496,23 +438,9 @@ JeecgBoot企业版本默认集成了activiti和flowable两套方案大家在
![](https://oscimg.oschina.net/oscnet/up-16c07e000278329b69b228ae3189814b8e9.png)
##### AI助手
![](https://oscimg.oschina.net/oscnet/up-7c6405641a40f56638999d52da0cb5b4343.png)
##### 流程设计
![](https://oscimg.oschina.net/oscnet/up-981ce174e4fbb48c8a2ce4ccfd7372e2994.png)
![输入图片说明](https://static.oschina.net/uploads/img/201907/05165142_yyQ7.png "在这里输入图片标题")
![输入图片说明](https://static.oschina.net/uploads/img/201904/14160917_9Ftz.png "在这里输入图片标题")
![输入图片说明](https://static.oschina.net/uploads/img/201904/14160633_u59G.png "在这里输入图片标题")
##### 简版流程设计
![](https://oscimg.oschina.net/oscnet/up-1dc0d052149ec675f3e4fad632b82b48add.png)
![](https://oscimg.oschina.net/oscnet/up-de31bc2f9d9b8332c554b0954cc73d79593.png)
![](https://oscimg.oschina.net/oscnet/up-7f83b25159663686d67ed080eb16068c3b4.png)
##### 仪表盘设计器
![](https://oscimg.oschina.net/oscnet/up-9c9d41288c31398d76b390bdd400f13a582.png)
@ -528,38 +456,6 @@ JeecgBoot企业版本默认集成了activiti和flowable两套方案大家在
![](https://oscimg.oschina.net/oscnet/up-f7e9cb2e3740f2d19ff63b40ec2dd554f96.png)
##### 表单设计器
![](https://oscimg.oschina.net/oscnet/up-5f8cb657615714b02190b355e59f60c5937.png)
![](https://oscimg.oschina.net/oscnet/up-d9659b2f324e33218476ec98c9b400e6508.png)
![](https://oscimg.oschina.net/oscnet/up-4868615395272d3206dbb960ade02dbc291.png)
##### 大屏设计器
![](https://oscimg.oschina.net/oscnet/up-402a6034124474bfef8dfc5b4b2bac1ce5c.png)
![](https://oscimg.oschina.net/oscnet/up-6f7ba2e2ebbeea0d203db8d69fd87644c9f.png)
![](https://oscimg.oschina.net/oscnet/up-ee8d34f318da466b8a6070a6e3111d12ce7.png)
![](https://oscimg.oschina.net/oscnet/up-6b81781b43086819049c4421206810667c5.png)
##### UNIAPP效果
![](https://oscimg.oschina.net/oscnet/up-aac943fbd26561879c57a41f7a406edf274.png)
![](https://oscimg.oschina.net/oscnet/up-9a44ba2e82b09c750629d12fafd7f60f553.png)
##### 零代码应用
![](https://oscimg.oschina.net/oscnet/up-4be29ae761b2615c8c54b3f668cd8432d9b.png)
![](https://oscimg.oschina.net/oscnet/up-787e76bc24b38ecc7ed19f338808d128255.png)
![](https://oscimg.oschina.net/oscnet/up-99d24a236c483362868523ad0d90f611487.png)
![](https://oscimg.oschina.net/oscnet/up-339a0f29d10449abc7724e3bcda802761c1.png)
![](https://oscimg.oschina.net/oscnet/up-b356670cdc14c609958c7619a537397c4b9.png)
##### 手机端
![](https://oscimg.oschina.net/oscnet/da543c5d0d57baab0cecaa4670c8b68c521.jpg)
@ -582,8 +478,62 @@ JeecgBoot企业版本默认集成了activiti和flowable两套方案大家在
##### 在线接口文档
![输入图片说明](https://static.oschina.net/uploads/img/201908/27095258_M2Xq.png "在这里输入图片标题")
![输入图片说明](https://static.oschina.net/uploads/img/201904/14160957_hN3X.png "在这里输入图片标题")
##### UNIAPP效果
![](https://oscimg.oschina.net/oscnet/up-aac943fbd26561879c57a41f7a406edf274.png)
![](https://oscimg.oschina.net/oscnet/up-9a44ba2e82b09c750629d12fafd7f60f553.png)
##### 大屏设计器
![](https://oscimg.oschina.net/oscnet/up-402a6034124474bfef8dfc5b4b2bac1ce5c.png)
![](https://oscimg.oschina.net/oscnet/up-6f7ba2e2ebbeea0d203db8d69fd87644c9f.png)
![](https://oscimg.oschina.net/oscnet/up-ee8d34f318da466b8a6070a6e3111d12ce7.png)
![](https://oscimg.oschina.net/oscnet/up-6b81781b43086819049c4421206810667c5.png)
##### 流程设计
![](https://oscimg.oschina.net/oscnet/up-981ce174e4fbb48c8a2ce4ccfd7372e2994.png)
![](https://oscimg.oschina.net/oscnet/up-1dc0d052149ec675f3e4fad632b82b48add.png)
![](https://oscimg.oschina.net/oscnet/up-de31bc2f9d9b8332c554b0954cc73d79593.png)
![输入图片说明](https://static.oschina.net/uploads/img/201907/05165142_yyQ7.png "在这里输入图片标题")
![输入图片说明](https://static.oschina.net/uploads/img/201904/14160917_9Ftz.png "在这里输入图片标题")
![输入图片说明](https://static.oschina.net/uploads/img/201904/14160633_u59G.png "在这里输入图片标题")
##### 表单设计器
![](https://oscimg.oschina.net/oscnet/up-5f8cb657615714b02190b355e59f60c5937.png)
![](https://oscimg.oschina.net/oscnet/up-d9659b2f324e33218476ec98c9b400e6508.png)
![](https://oscimg.oschina.net/oscnet/up-4868615395272d3206dbb960ade02dbc291.png)
## 捐赠
如果觉得还不错,请作者喝杯咖啡吧 ☺
![](https://static.oschina.net/uploads/img/201903/08155608_0EFX.png)
### 流程引擎推荐
大家在使用本开源项目时,如果想进一步集成流程引擎,推荐结合贺波老师的书 [《深入Activiti流程引擎核心原理与高阶实战》](https://item.m.jd.com/product/13928958.html?gx=RnAomTM2bmCImZxDqYAkVCoIHuIYVqc)
<img src="https://jeecgos.oss-cn-beijing.aliyuncs.com/files/tuijian20231220161656.png" width="25%" height="auto">

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,11 +0,0 @@
-- 新增风格一对多内嵌和Tab风格
INSERT INTO sys_permission (id, parent_id, name, url, component, is_route, component_name, redirect, menu_type, perms, perms_type, sort_no, always_show, icon, is_leaf, keep_alive, hidden, hide_tab, description, create_by, create_time, update_by, update_time, del_flag, rule_flag, status, internal_or_external)
VALUES ('1691031996d5931315212', '1455100420297859074', 'AUTO在线一对多内嵌', '/online/cgformInnerTableList/:id', 'super/online/cgform/auto/innerTable/OnlCgformInnerTableList', 1, '', NULL, 1, NULL, '0', 1.00, 0, NULL, 1, 0, 1, 0, NULL, 'admin', '2023-08-14 18:20:20', 'admin', '2023-08-14 18:46:18', 0, 0, NULL, 0);
INSERT INTO sys_permission (id, parent_id, name, url, component, is_route, component_name, redirect, menu_type, perms, perms_type, sort_no, always_show, icon, is_leaf, keep_alive, hidden, hide_tab, description, create_by, create_time, update_by, update_time, del_flag, rule_flag, status, internal_or_external)
VALUES ('1691031996d5931315213', '1455100420297859074', 'AUTO在线Tab风格', '/online/cgformTabList/:id', 'super/online/cgform/auto/tab/OnlCgformTabList', 1, '', NULL, 1, NULL, '0', 1.00, 0, NULL, 1, 0, 1, 0, NULL, 'admin', '2023-08-14 18:20:20', 'admin', '2023-08-14 18:46:18', 0, 0, NULL, 0);
-- 安全online敏感接口加权限注解sql解析接口同步数据库接口导入表接口
INSERT INTO sys_permission (id, parent_id, name, url, component, is_route, component_name, redirect, menu_type, perms, perms_type, sort_no, always_show, icon, is_leaf, keep_alive, hidden, hide_tab, description, create_by, create_time, update_by, update_time, del_flag, rule_flag, status, internal_or_external) VALUES ('1699374704168534017', '1460888189937176577', 'SQL解析', NULL, NULL, 0, NULL, NULL, 2, 'online:report:parseSql', '1', NULL, 0, NULL, 1, 0, 0, 0, NULL, 'admin', '2023-09-06 18:51:17', NULL, NULL, 0, 0, '1', 0);
INSERT INTO sys_permission (id, parent_id, name, url, component, is_route, component_name, redirect, menu_type, perms, perms_type, sort_no, always_show, icon, is_leaf, keep_alive, hidden, hide_tab, description, create_by, create_time, update_by, update_time, del_flag, rule_flag, status, internal_or_external) VALUES ('1699374509749960705', '1455101470794850305', '查询数据库表名', NULL, NULL, 0, NULL, NULL, 2, 'online:form:queryTables', '1', NULL, 0, NULL, 1, 0, 0, 0, NULL, 'admin', '2023-09-06 18:50:31', NULL, NULL, 0, 0, '1', 0);
INSERT INTO sys_permission (id, parent_id, name, url, component, is_route, component_name, redirect, menu_type, perms, perms_type, sort_no, always_show, icon, is_leaf, keep_alive, hidden, hide_tab, description, create_by, create_time, update_by, update_time, del_flag, rule_flag, status, internal_or_external) VALUES ('1699374269152100354', '1455101470794850305', '同步数据库', NULL, NULL, 0, NULL, NULL, 2, 'online:form:syncDb', '1', NULL, 0, NULL, 1, 0, 0, 0, NULL, 'admin', '2023-09-06 18:49:33', NULL, NULL, 0, 0, '1', 0);
update sys_permission set is_leaf=0 where id in ('1460888189937176577','1455101470794850305');

View File

@ -1,45 +0,0 @@
CREATE TABLE `oauth2_registered_client` (
`id` varchar(100) NOT NULL,
`client_id` varchar(100) NOT NULL,
`client_id_issued_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`client_secret` varchar(200) DEFAULT NULL,
`client_secret_expires_at` timestamp NULL DEFAULT NULL,
`client_name` varchar(200) NOT NULL,
`client_authentication_methods` varchar(1000) NOT NULL,
`authorization_grant_types` varchar(1000) NOT NULL,
`redirect_uris` varchar(1000) DEFAULT NULL,
`post_logout_redirect_uris` varchar(1000) DEFAULT NULL,
`scopes` varchar(1000) NOT NULL,
`client_settings` varchar(2000) NOT NULL,
`token_settings` varchar(2000) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
INSERT INTO `oauth2_registered_client`
(`id`,
`client_id`,
`client_id_issued_at`,
`client_secret`,
`client_secret_expires_at`,
`client_name`,
`client_authentication_methods`,
`authorization_grant_types`,
`redirect_uris`,
`post_logout_redirect_uris`,
`scopes`,
`client_settings`,
`token_settings`)
VALUES
('3eacac0e-0de9-4727-9a64-6bdd4be2ee1f',
'jeecg-client',
now(),
'secret',
null,
'3eacac0e-0de9-4727-9a64-6bdd4be2ee1f',
'client_secret_basic',
'refresh_token,authorization_code,password,app,phone,social',
'http://127.0.0.1:8080/jeecg-',
'http://127.0.0.1:8080/',
'*',
'{"@class":"java.util.Collections$UnmodifiableMap","settings.client.require-proof-key":false,"settings.client.require-authorization-consent":true}',
'{"@class":"java.util.Collections$UnmodifiableMap","settings.token.reuse-refresh-tokens":true,"settings.token.id-token-signature-algorithm":["org.springframework.security.oauth2.jose.jws.SignatureAlgorithm","RS256"],"settings.token.access-token-time-to-live":["java.time.Duration",300000.000000000],"settings.token.access-token-format":{"@class":"org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat","value":"self-contained"},"settings.token.refresh-token-time-to-live":["java.time.Duration",3600.000000000],"settings.token.authorization-code-time-to-live":["java.time.Duration",300000.000000000],"settings.token.device-code-time-to-live":["java.time.Duration",300000.000000000]}');

View File

@ -1,11 +0,0 @@
版本升级方法?
JeecgBoot属于平台级产品每次升级改动内容较多目前做不到平滑升级。
升级方案建议:
1.代码升级 => 本地版本通过svn或者git做好主干在分支上做业务开发jeecg每次版本发布可以手工覆盖主干的代码对比合并代码
2.数据库升级 => 针对数据库我们每次发布会提供增量升级SQL可以通过执行增量SQL实现数据库的升级。
3.兼容问题 => 每次版本发布会针对不兼容地方标注说明,需要手工修改不兼容的代码。
注意: 升级sql目前只提供mysql版本执行完脚步后新菜单需要手工进行角色授权刷新首页才会出现。
【20230820 放开了系统管理等模块权限注解,如果没权限请通过角色授权授权对应的按钮权限】

15
db/版本升级说明.md Normal file
View File

@ -0,0 +1,15 @@
# 版本升级方法
> JeecgBoot属于平台级产品每次升级改动较大目前做不到平滑升级。
### 增量升级方案
#### 1.代码合并
本地通过svn或git做好主干在分支上做业务开发jeecg每次版本发布可以手工覆盖主干的代码对比合并代码
#### 2.数据库升级
- 从3.6.2+版本增加flyway自动升级数据库机制支持 mysql5.7、mysql8;
- 其他库请手工执行SQL, 目录: `jeecg-module-system\jeecg-system-start\src\main\resources\flyway\sql\mysql`
> 注意: 升级sql只提供mysql版本如果有权限升级, 还需要手工角色授权,退出重新登录才好使。
#### 3.兼容问题
每次发版,会针对不兼容地方重点说明。

View File

@ -4,15 +4,11 @@
<parent>
<groupId>org.jeecgframework.boot</groupId>
<artifactId>jeecg-boot-parent</artifactId>
<version>3.6.1</version>
<version>3.7.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>jeecg-boot-base-core</artifactId>
<properties>
<spring-boot.version>3.1.5</spring-boot.version>
</properties>
<repositories>
<repository>
<id>aliyun</id>
@ -47,22 +43,12 @@
<!--jeecg-tools-->
<dependency>
<groupId>org.jeecgframework.boot</groupId>
<artifactId>jeecg-boot-common3</artifactId>
<artifactId>jeecg-boot-common</artifactId>
</dependency>
<!--集成springmvc框架并实现自动配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<!-- websocket -->
<dependency>
@ -96,7 +82,7 @@
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.version}</version>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
@ -119,14 +105,14 @@
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-3-starter</artifactId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- 动态数据源 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>${dynamic-datasource-spring-boot-starter.version}</version>
</dependency>
@ -159,6 +145,24 @@
<version>${postgresql.version}</version>
<scope>runtime</scope>
</dependency>
<!--人大金仓驱动 版本号V008R006C005B0013 -->
<dependency>
<groupId>org.jeecgframework</groupId>
<artifactId>kingbase8</artifactId>
<version>${kingbase8.version}</version>
<scope>runtime</scope>
</dependency>
<!--达梦数据库驱动 版本号1-3-26-2023.07.26-197096-20046-ENT -->
<dependency>
<groupId>com.dameng</groupId>
<artifactId>Dm8JdbcDriver18</artifactId>
<version>${dm8.version}</version>
</dependency>
<dependency>
<groupId>com.dameng</groupId>
<artifactId>DmDialect-for-hibernate5.0</artifactId>
<version>${dm8.version}</version>
</dependency>
<!-- Quartz定时任务 -->
<dependency>
@ -173,25 +177,38 @@
<version>${java-jwt.version}</version>
</dependency>
<!--shiro-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>${shiro.version}</version>
</dependency>
<!-- shiro-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<!-- 添加spring security cas支持 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>${shiro-redis.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
</exclusion>
<exclusion>
<artifactId>checkstyle</artifactId>
<groupId>com.puppycrawl.tools</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- knife4j -->
<!-- <dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
<version>${knife4j-spring-boot-starter.version}</version>
</dependency>
@ -205,7 +222,7 @@
<!-- AutoPoi Excel工具类-->
<dependency>
<groupId>org.jeecgframework.boot3</groupId>
<groupId>org.jeecgframework</groupId>
<artifactId>autopoi-web</artifactId>
<version>${autopoi-web.version}</version>
<exclusions>
@ -248,16 +265,6 @@
<dependency>
<groupId>com.xkcoding.justauth</groupId>
<artifactId>justauth-spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
@ -281,6 +288,11 @@
<groupId>cn.hutool</groupId>
<artifactId>hutool-crypto</artifactId>
</dependency>
</dependencies>
<!-- chatgpt -->
<dependency>
<groupId>org.jeecgframework.boot</groupId>
<artifactId>jeecg-boot-starter-chatgpt</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -1,21 +0,0 @@
package org.apache.shiro;
import org.apache.shiro.subject.Subject;
/**
* 兼容处理Online功能使用处理请勿修改
* @author eightmonth@qq.com
* @date 2024/4/29 14:05
*/
public class SecurityUtils {
public static Subject getSubject() {
return new Subject() {
@Override
public Object getPrincipal() {
return Subject.super.getPrincipal();
}
};
}
}

View File

@ -1,14 +0,0 @@
package org.apache.shiro.subject;
import org.jeecg.config.security.utils.SecureUtil;
/**
* 兼容处理Online功能使用处理请勿修改
* @author eightmonth@qq.com
* @date 2024/4/29 14:18
*/
public interface Subject {
default Object getPrincipal() {
return SecureUtil.currentUser();
}
}

View File

@ -1,6 +1,5 @@
package org.jeecg.common.api;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.system.vo.*;
import java.util.List;
@ -20,13 +19,20 @@ public interface CommonAPI {
*/
Set<String> queryUserRoles(String username);
/**
* 1查询用户角色信息
* @param userId
* @return
*/
Set<String> queryUserRolesById(String userId);
/**
* 2查询用户权限信息
* @param username
* @param userId
* @return
*/
Set<String> queryUserAuths(String username);
Set<String> queryUserAuths(String userId);
/**
* 3根据 id 查询数据库中存储的 DynamicDataSourceModel
@ -52,11 +58,11 @@ public interface CommonAPI {
public LoginUser getUserByName(String username);
/**
* 5根据用户手机号查询用户信息
* 5根据用户号查询用户Id
* @param username
* @return
*/
public LoginUser getUserByPhone(String phone);
public String getUserIdByName(String username);
/**
@ -125,41 +131,17 @@ public interface CommonAPI {
*/
Map<String, List<DictModel>> translateManyDict(String dictCodes, String keys);
//update-begin---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
/**
* 15 字典表的 翻译,可批量
* @param table
* @param text
* @param code
* @param keys 多个用逗号分割
* @param dataSource 数据源
* @return
*/
List<DictModel> translateDictFromTableByKeys(String table, String text, String code, String keys);
/**
* 登录加载系统字典
* @return
*/
Map<String,List<DictModel>> queryAllDictItems();
/**
* 查询SysDepart集合
* @param userId
* @return
*/
List<SysDepartModel> queryUserDeparts(String userId);
/**
* 根据用户名设置部门ID
* @param username
* @param orgCode
*/
void updateUserDepart(String username,String orgCode,Integer loginTenantId);
/**
* 设置登录租户
* @param username
* @return
*/
JSONObject setLoginTenant(String username);
List<DictModel> translateDictFromTableByKeys(String table, String text, String code, String keys, String dataSource);
//update-end---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
}

View File

@ -17,6 +17,8 @@ public class DataLogDTO {
private String type;
private String createName;
public DataLogDTO(){
}

View File

@ -2,7 +2,7 @@ package org.jeecg.common.api.dto;
import lombok.Data;
import jakarta.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
/**

View File

@ -1,5 +1,6 @@
package org.jeecg.common.api.dto;
import lombok.Data;
import org.jeecg.common.aspect.annotation.Dict;
import org.jeecg.common.system.vo.LoginUser;
import java.io.Serializable;
import java.util.Date;
@ -55,6 +56,11 @@ public class LogDTO implements Serializable {
*/
private Integer tenantId;
/**
* 客户终端类型 pc:电脑端 app:手机端 h5:移动网页端
*/
private String clientType;
public LogDTO(){
}

View File

@ -30,6 +30,13 @@ public class OnlineAuthDTO implements Serializable {
*/
private String onlineFormUrl;
//update-begin---author:chenrui ---date:20240123 for[QQYUN-7992]【online】工单申请下的online表单未配置online表单开发菜单操作报错无权限------------
/**
* online工单的地址
*/
private String onlineWorkOrderUrl;
//update-end---author:chenrui ---date:20240123 for[QQYUN-7992]【online】工单申请下的online表单未配置online表单开发菜单操作报错无权限------------
public OnlineAuthDTO(){
}

View File

@ -1,7 +1,8 @@
package org.jeecg.common.api.vo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.jeecg.common.constant.CommonConstant;
@ -14,7 +15,7 @@ import java.io.Serializable;
* @date 2019年1月19日
*/
@Data
@Schema(description="接口返回对象")
@ApiModel(value="接口返回对象", description="接口返回对象")
public class Result<T> implements Serializable {
private static final long serialVersionUID = 1L;
@ -22,31 +23,31 @@ public class Result<T> implements Serializable {
/**
* 成功标志
*/
@Schema(description = "成功标志")
@ApiModelProperty(value = "成功标志")
private boolean success = true;
/**
* 返回处理消息
*/
@Schema(description = "返回处理消息")
@ApiModelProperty(value = "返回处理消息")
private String message = "";
/**
* 返回代码
*/
@Schema(description = "返回代码")
@ApiModelProperty(value = "返回代码")
private Integer code = 0;
/**
* 返回数据对象 data
*/
@Schema(description = "返回数据对象")
@ApiModelProperty(value = "返回数据对象")
private T result;
/**
* 时间戳
*/
@Schema(description = "时间戳")
@ApiModelProperty(value = "时间戳")
private long timestamp = System.currentTimeMillis();
public Result() {

View File

@ -1,8 +1,8 @@
package org.jeecg.common.aspect;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
@ -15,21 +15,19 @@ import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ModuleType;
import org.jeecg.common.constant.enums.OperateTypeEnum;
import org.jeecg.config.security.utils.SecureUtil;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.IpUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
@ -102,7 +100,7 @@ public class AutoLogAspect {
//设置IP地址
dto.setIp(IpUtils.getIpAddr(request));
//获取登录用户信息
LoginUser sysUser = SecureUtil.currentUser();
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
if(sysUser!=null){
dto.setUserid(sysUser.getUsername());
dto.setUsername(sysUser.getRealname());

View File

@ -52,7 +52,9 @@ public class DictAspect {
/**
* 定义切点Pointcut
*/
@Pointcut("execution(public * org.jeecg.modules..*.*Controller.*(..)) || @annotation(org.jeecg.common.aspect.annotation.AutoDict)")
@Pointcut("(@within(org.springframework.web.bind.annotation.RestController) || " +
"@within(org.springframework.stereotype.Controller) || @annotation(org.jeecg.common.aspect.annotation.AutoDict)) " +
"&& execution(public org.jeecg.common.api.vo.Result org.jeecg..*.*(..))")
public void excudeService() {
}
@ -92,7 +94,8 @@ public class DictAspect {
* @param result
*/
private Object parseDictText(Object result) {
if (result instanceof Result) {
//if (result instanceof Result) {
if (true) {
if (((Result) result).getResult() instanceof IPage) {
List<JSONObject> items = new ArrayList<>();
@ -140,11 +143,15 @@ public class DictAspect {
String code = field.getAnnotation(Dict.class).dicCode();
String text = field.getAnnotation(Dict.class).dicText();
String table = field.getAnnotation(Dict.class).dictTable();
//update-begin---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
String dataSource = field.getAnnotation(Dict.class).ds();
//update-end---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
List<String> dataList;
String dictCode = code;
if (!StringUtils.isEmpty(table)) {
dictCode = String.format("%s,%s,%s", table, text, code);
//update-begin---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
dictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource);
//update-end---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
}
dataList = dataListMap.computeIfAbsent(dictCode, k -> new ArrayList<>());
this.listAddAllDeduplicate(dataList, Arrays.asList(value.split(",")));
@ -169,10 +176,15 @@ public class DictAspect {
String code = field.getAnnotation(Dict.class).dicCode();
String text = field.getAnnotation(Dict.class).dicText();
String table = field.getAnnotation(Dict.class).dictTable();
//update-begin---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
// 自定义的字典表数据源
String dataSource = field.getAnnotation(Dict.class).ds();
//update-end---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
String fieldDictCode = code;
if (!StringUtils.isEmpty(table)) {
fieldDictCode = String.format("%s,%s,%s", table, text, code);
//update-begin---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
fieldDictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource);
//update-end---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
}
String value = record.getString(field.getName());
@ -274,9 +286,25 @@ public class DictAspect {
String[] arr = dictCode.split(",");
String table = arr[0], text = arr[1], code = arr[2];
String values = String.join(",", needTranslDataTable);
//update-begin---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
// 自定义的数据源
String dataSource = null;
if (arr.length > 3) {
dataSource = arr[3];
}
//update-end---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
log.debug("translateDictFromTableByKeys.dictCode:" + dictCode);
log.debug("translateDictFromTableByKeys.values:" + values);
List<DictModel> texts = commonApi.translateDictFromTableByKeys(table, text, code, values);
//update-begin---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
//update-begin---author:wangshuai---date:2024-01-09---for:微服务下为空报错没有参数需要传递空字符串---
if(null == dataSource){
dataSource = "";
}
//update-end---author:wangshuai---date:2024-01-09---for:微服务下为空报错没有参数需要传递空字符串---
List<DictModel> texts = commonApi.translateDictFromTableByKeys(table, text, code, values, dataSource);
//update-end---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
log.debug("translateDictFromTableByKeys.result:" + texts);
List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
list.addAll(texts);

View File

@ -21,7 +21,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

View File

@ -39,4 +39,16 @@ public @interface Dict {
* @return 返回类型: String
*/
String dictTable() default "";
//update-begin---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
/**
* 方法描述: 数据字典表所在数据源名称
* 作 者: chenrui
* 日 期: 2023年12月20日-下午4:58
*
* @return 返回类型: String
*/
String ds() default "";
//update-end---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
}

View File

@ -36,6 +36,16 @@ public interface CommonConstant {
*/
int LOG_TYPE_2 = 2;
/**
* 系统日志类型: 租户操作日志
*/
int LOG_TYPE_3 = 3;
/**
* 系统日志类型: 异常
*/
int LOG_TYPE_4 = 4;
/**
* 操作日志类型: 查询
*/
@ -69,6 +79,8 @@ public interface CommonConstant {
/** {@code 500 Server Error} (HTTP/1.0 - RFC 1945) */
Integer SC_INTERNAL_SERVER_ERROR_500 = 500;
/** {@code 404 Not Found} (HTTP/1.0 - RFC 1945) */
Integer SC_INTERNAL_NOT_FOUND_404 = 404;
/** {@code 200 OK} (HTTP/1.0 - RFC 1945) */
Integer SC_OK_200 = 200;
@ -78,7 +90,7 @@ public interface CommonConstant {
/** 登录用户Shiro权限缓存KEY前缀 */
public static String PREFIX_USER_SHIRO_CACHE = "shiro:cache:org.jeecg.config.shiro.ShiroRealm.authorizationCache:";
/** 登录用户Token令牌缓存KEY前缀 */
String PREFIX_USER_TOKEN = "token::jeecg-client::";
String PREFIX_USER_TOKEN = "prefix_user_token:";
// /** Token缓存时间3600秒即一小时 */
// int TOKEN_EXPIRE_TIME = 3600;
@ -284,6 +296,10 @@ public interface CommonConstant {
* 在线聊天 用户好友缓存前缀
*/
String IM_PREFIX_USER_FRIEND_CACHE = "sys:cache:im:im_prefix_user_friend_";
/**
* 缓存用户id与用户名关系
*/
String SYS_USER_ID_MAPPING_CACHE = "sys:cache:user:id_mapping";
/**
* 考勤补卡业务状态 1同意 2不同意
@ -375,6 +391,8 @@ public interface CommonConstant {
/**前端vue3版本Header参数名*/
String VERSION="X-Version";
String VERSION_V3 = "v3";
/**存储在线程变量里的动态表名*/
String DYNAMIC_TABLE_NAME="DYNAMIC_TABLE_NAME";
/**
@ -573,4 +591,30 @@ public interface CommonConstant {
public static final String SAAS_MODE_TENANT = "tenant";
//update-end---author:scott ---date::2023-09-10 for积木报表常量----
//update-begin---author:wangshuai---date:2024-04-07---for:修改手机号常量---
/**
* 修改手机号短信验证码redis-key的前缀
*/
String CHANGE_PHONE_REDIS_KEY_PRE = "sys:cache:phone:change_phone_msg:";
/**
* 缓存用户最后一次收到消息通知的时间 KEY
*/
String CACHE_KEY_USER_LAST_ANNOUNT_TIME_1HOUR = "sys:cache:userinfo:user_last_annount_time::%s";
/**
* 验证原手机号
*/
String VERIFY_ORIGINAL_PHONE = "verifyOriginalPhone";
/**
* 修改手机号
*/
String UPDATE_PHONE = "updatePhone";
//update-end---author:wangshuai---date:2024-04-07---for:修改手机号常量---
/**
* 修改手机号验证码请求次数超出
*/
Integer PHONE_SMS_FAIL_CODE = 40002;
}

View File

@ -18,6 +18,9 @@ public interface DataBaseConstant {
/**postgreSQL达梦数据库*/
public static final String DB_TYPE_POSTGRESQL = "POSTGRESQL";
/**人大金仓数据库*/
public static final String DB_TYPE_KINGBASEES = "KINGBASEES";
/**sqlserver数据库*/
public static final String DB_TYPE_SQLSERVER = "SQLSERVER";
@ -55,6 +58,22 @@ public interface DataBaseConstant {
* 数据-所属机构编码
*/
public static final String SYS_MULTI_ORG_CODE_TABLE = "sys_multi_org_code";
/**
* 数据-所属机构ID
*/
public static final String SYS_ORG_ID = "sysOrgId";
/**
* 数据-所属机构ID
*/
public static final String SYS_ORG_ID_TABLE = "sys_org_id";
/**
* 数据-所属角色code多个逗号分割
*/
public static final String SYS_ROLE_CODE = "sysRoleCode";
/**
* 数据-所属角色code多个逗号分割
*/
public static final String SYS_ROLE_CODE_TABLE = "sys_role_code";
/**
* 数据-系统用户编码(对应登录用户账号)
*/
@ -63,7 +82,14 @@ public interface DataBaseConstant {
* 数据-系统用户编码(对应登录用户账号)
*/
public static final String SYS_USER_CODE_TABLE = "sys_user_code";
/**
* 登录用户ID
*/
public static final String SYS_USER_ID = "sysUserId";
/**
* 登录用户ID
*/
public static final String SYS_USER_ID_TABLE = "sys_user_id";
/**
* 登录用户真实姓名
*/

View File

@ -34,17 +34,22 @@ public interface ServiceNameConstants {
*/
String SERVICE_DEMO = "jeecg-demo";
/**
* 微服务名:online在线模块
* 微服务名:joa模块
*/
String SERVICE_ONLINE = "jeecg-online";
/**
* 微服务名OA模块
*/
String SERVICE_EOA = "jeecg-eoa";
/**
* 微服务名:表单设计模块
*/
String SERVICE_FORM = "jeecg-desform";
String SERVICE_JOA = "jeecg-joa";
// /**
// * 微服务名online在线模块
// */
// String SERVICE_ONLINE = "jeecg-online";
// /**
// * 微服务名OA模块
// */
// String SERVICE_EOA = "jeecg-eoa";
// /**
// * 微服务名:表单设计模块
// */
// String SERVICE_FORM = "jeecg-desform";
/**
* gateway通过header传递根路径 basePath

View File

@ -23,7 +23,7 @@ public enum CgformEnum {
/**
* 多表jvxe风格
* */
JVXE_TABLE(2, "jvxe", "/jeecg/code-template-online", "jvxe.onetomany", "JVXE风格" ,new String[]{"vue3","vue","vue3Native"}),
JVXE_TABLE(2, "jvxe", "/jeecg/code-template-online", "jvxe.onetomany", "默认风格" ,new String[]{"vue3","vue","vue3Native"}),
/**
* 多表 (erp风格)

View File

@ -0,0 +1,23 @@
package org.jeecg.common.constant.enums;
/**
* 客户终端类型
*/
public enum ClientTerminalTypeEnum {
PC("pc", "电脑终端"),
H5("h5", "移动网页端"),
APP("app", "手机app端");
private String key;
private String text;
ClientTerminalTypeEnum(String value, String text) {
this.key = value;
this.text = text;
}
public String getKey() {
return this.key;
}
}

View File

@ -0,0 +1,27 @@
package org.jeecg.common.constant.enums;
/**
* 日期预设范围枚举
*/
public enum DateRangeEnum {
// 今天
TODAY,
// 昨天
YESTERDAY,
// 明天
TOMORROW,
// 本周
THIS_WEEK,
// 上周
LAST_WEEK,
// 下周
NEXT_WEEK,
// 过去七天
LAST_7_DAYS,
// 本月
THIS_MONTH,
// 上月
LAST_MONTH,
// 下月
NEXT_MONTH,
}

View File

@ -12,6 +12,8 @@ public enum DySmsEnum {
LOGIN_TEMPLATE_CODE("SMS_175435174","敲敲云","code"),
/**忘记密码短信模板编码*/
FORGET_PASSWORD_TEMPLATE_CODE("SMS_175435174","敲敲云","code"),
/**修改密码短信模板编码*/
CHANGE_PASSWORD_TEMPLATE_CODE("SMS_465391221","敲敲云","code"),
/**注册账号短信模板编码*/
REGISTER_TEMPLATE_CODE("SMS_175430166","敲敲云","code"),
/**会议通知*/

View File

@ -13,12 +13,16 @@ import java.util.List;
public enum RoleIndexConfigEnum {
/**首页自定义 admin*/
ADMIN("admin", "dashboard/Analysis"),
// ADMIN("admin", "dashboard/Analysis"),
//TEST("test", "dashboard/IndexChart"),
/**首页自定义 hr*/
HR("hr", "dashboard/IndexBdc");
// HR("hr", "dashboard/IndexBdc");
//DM("dm", "dashboard/IndexTask"),
// 注:此值仅为防止报错,无任何实际意义
ROLE_INDEX_CONFIG_ENUM("RoleIndexConfigEnumDefault", "dashboard/Analysis");
/**
* 角色编码
*/

View File

@ -0,0 +1,87 @@
package org.jeecg.common.desensitization;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.desensitization.annotation.Sensitive;
import org.jeecg.common.desensitization.enums.SensitiveEnum;
import org.jeecg.common.desensitization.util.SensitiveInfoUtil;
import org.jeecg.common.util.encryption.AesEncryptUtil;
import java.io.IOException;
import java.util.Objects;
/**
* @author eightmonth@qq.com
* @date 2024/6/19 10:43
*/
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class SensitiveSerialize extends JsonSerializer<String> implements ContextualSerializer {
private SensitiveEnum type;
@Override
public void serialize(String data, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
switch (type){
case ENCODE:
try {
jsonGenerator.writeString(AesEncryptUtil.encrypt(data));
} catch (Exception exception) {
log.error("数据加密错误", exception.getMessage());
jsonGenerator.writeString(data);
}
break;
case CHINESE_NAME:
jsonGenerator.writeString(SensitiveInfoUtil.chineseName(data));
break;
case ID_CARD:
jsonGenerator.writeString(SensitiveInfoUtil.idCardNum(data));
break;
case FIXED_PHONE:
jsonGenerator.writeString(SensitiveInfoUtil.fixedPhone(data));
break;
case MOBILE_PHONE:
jsonGenerator.writeString(SensitiveInfoUtil.mobilePhone(data));
break;
case ADDRESS:
jsonGenerator.writeString(SensitiveInfoUtil.address(data, 3));
break;
case EMAIL:
jsonGenerator.writeString(SensitiveInfoUtil.email(data));
break;
case BANK_CARD:
jsonGenerator.writeString(SensitiveInfoUtil.bankCard(data));
break;
case CNAPS_CODE:
jsonGenerator.writeString(SensitiveInfoUtil.cnapsCode(data));
break;
default:
jsonGenerator.writeString(data);
}
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
if (beanProperty != null) {
if (Objects.equals(beanProperty.getType().getRawClass(), String.class)) {
Sensitive sensitive = beanProperty.getAnnotation(Sensitive.class);
if (sensitive == null) {
sensitive = beanProperty.getContextAnnotation(Sensitive.class);
}
if (sensitive != null) {
return new SensitiveSerialize(sensitive.type());
}
}
return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
}
return serializerProvider.findNullValueSerializer(null);
}
}

View File

@ -0,0 +1,26 @@
package org.jeecg.common.desensitization.annotation;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.jeecg.common.desensitization.SensitiveSerialize;
import org.jeecg.common.desensitization.enums.SensitiveEnum;
import java.lang.annotation.*;
/**
* 在字段上定义 标识字段存储的信息是敏感的
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JacksonAnnotationsInside
@JsonSerialize(using = SensitiveSerialize.class)
public @interface Sensitive {
/**
* 不同类型处理不同
* @return
*/
SensitiveEnum type() default SensitiveEnum.ENCODE;
}

View File

@ -198,7 +198,7 @@ public class SensitiveInfoUtil {
* @param fullName 全名
* @return <例子:李**>
*/
private static String chineseName(String fullName) {
public static String chineseName(String fullName) {
if (oConvertUtils.isEmpty(fullName)) {
return "";
}
@ -211,7 +211,7 @@ public class SensitiveInfoUtil {
* @param firstName 名
* @return <例子:李**>
*/
private static String chineseName(String familyName, String firstName) {
public static String chineseName(String familyName, String firstName) {
if (oConvertUtils.isEmpty(familyName) || oConvertUtils.isEmpty(firstName)) {
return "";
}
@ -223,7 +223,7 @@ public class SensitiveInfoUtil {
* @param id 身份证号
* @return <例子:*************5762>
*/
private static String idCardNum(String id) {
public static String idCardNum(String id) {
if (oConvertUtils.isEmpty(id)) {
return "";
}
@ -236,7 +236,7 @@ public class SensitiveInfoUtil {
* @param num 固定电话
* @return <例子:****1234>
*/
private static String fixedPhone(String num) {
public static String fixedPhone(String num) {
if (oConvertUtils.isEmpty(num)) {
return "";
}
@ -248,7 +248,7 @@ public class SensitiveInfoUtil {
* @param num 手机号码
* @return <例子:138******1234>
*/
private static String mobilePhone(String num) {
public static String mobilePhone(String num) {
if (oConvertUtils.isEmpty(num)) {
return "";
}
@ -265,7 +265,7 @@ public class SensitiveInfoUtil {
* @param sensitiveSize 敏感信息长度
* @return <例子:北京市海淀区****>
*/
private static String address(String address, int sensitiveSize) {
public static String address(String address, int sensitiveSize) {
if (oConvertUtils.isEmpty(address)) {
return "";
}
@ -281,7 +281,7 @@ public class SensitiveInfoUtil {
* @param email 电子邮箱
* @return <例子:g**@163.com>
*/
private static String email(String email) {
public static String email(String email) {
if (oConvertUtils.isEmpty(email)) {
return "";
}
@ -300,7 +300,7 @@ public class SensitiveInfoUtil {
* @param cardNum 银行卡号
* @return <例子:6222600**********1234>
*/
private static String bankCard(String cardNum) {
public static String bankCard(String cardNum) {
if (oConvertUtils.isEmpty(cardNum)) {
return "";
}
@ -312,7 +312,7 @@ public class SensitiveInfoUtil {
* @param code 公司开户银行联号
* @return <例子:12********>
*/
private static String cnapsCode(String code) {
public static String cnapsCode(String code) {
if (oConvertUtils.isEmpty(code)) {
return "";
}
@ -326,7 +326,7 @@ public class SensitiveInfoUtil {
* @param reservedLength 保留长度
* @return 格式化后的字符串
*/
private static String formatRight(String str, int reservedLength){
public static String formatRight(String str, int reservedLength){
String name = str.substring(0, reservedLength);
String stars = String.join("", Collections.nCopies(str.length()-reservedLength, "*"));
return name + stars;
@ -338,7 +338,7 @@ public class SensitiveInfoUtil {
* @param reservedLength 保留长度
* @return 格式化后的字符串
*/
private static String formatLeft(String str, int reservedLength){
public static String formatLeft(String str, int reservedLength){
int len = str.length();
String show = str.substring(len-reservedLength);
String stars = String.join("", Collections.nCopies(len-reservedLength, "*"));
@ -352,7 +352,7 @@ public class SensitiveInfoUtil {
* @param endLen 结尾保留长度
* @return 格式化后的字符串
*/
private static String formatBetween(String str, int beginLen, int endLen){
public static String formatBetween(String str, int beginLen, int endLen){
int len = str.length();
String begin = str.substring(0, beginLen);
String end = str.substring(len-endLen);

View File

@ -0,0 +1,40 @@
package org.jeecg.common.exception;
import org.jeecg.common.constant.CommonConstant;
/**
* @Description: 业务提醒异常(用于操作业务提醒)
* @date: 2024-04-26
* @author: scott
*/
public class JeecgBootBizTipException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* 返回给前端的错误code
*/
private int errCode = CommonConstant.SC_INTERNAL_SERVER_ERROR_500;
public JeecgBootBizTipException(String message){
super(message);
}
public JeecgBootBizTipException(String message, int errCode){
super(message);
this.errCode = errCode;
}
public int getErrCode() {
return errCode;
}
public JeecgBootBizTipException(Throwable cause)
{
super(cause);
}
public JeecgBootBizTipException(String message, Throwable cause)
{
super(message,cause);
}
}

View File

@ -1,5 +1,7 @@
package org.jeecg.common.exception;
import org.jeecg.common.constant.CommonConstant;
/**
* @Description: jeecg-boot自定义异常
* @author: jeecg-boot
@ -7,10 +9,24 @@ package org.jeecg.common.exception;
public class JeecgBootException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* 返回给前端的错误code
*/
private int errCode = CommonConstant.SC_INTERNAL_SERVER_ERROR_500;
public JeecgBootException(String message){
super(message);
}
public JeecgBootException(String message, int errCode){
super(message);
this.errCode = errCode;
}
public int getErrCode() {
return errCode;
}
public JeecgBootException(Throwable cause)
{
super(cause);

View File

@ -2,22 +2,38 @@ package org.jeecg.common.exception;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.jeecg.common.api.dto.LogDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ClientTerminalTypeEnum;
import org.jeecg.common.enums.SentinelErrorInfoEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.BrowserUtils;
import org.jeecg.common.util.IpUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.springframework.beans.BeansException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.connection.PoolException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.CollectionUtils;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* 异常处理器
*
@ -28,23 +44,8 @@ import org.springframework.web.servlet.NoHandlerFoundException;
@Slf4j
public class JeecgBootExceptionHandler {
/**
* 验证码错误异常
*/
@ExceptionHandler(JeecgCaptchaException.class)
@ResponseStatus(HttpStatus.OK)
public Result<?> handleJeecgCaptchaException(JeecgCaptchaException e) {
log.error(e.getMessage(), e);
return Result.error(e.getCode(), e.getMessage());
}
@ExceptionHandler(AuthenticationException.class)
@ResponseStatus(HttpStatus.OK)
public Result<?> handleJeecgCaptchaException(AuthenticationException e) {
log.error(e.getMessage(), e);
return Result.error(401, e.getMessage());
}
@Resource
BaseCommonService baseCommonService;
/**
* 处理自定义异常
@ -52,7 +53,17 @@ public class JeecgBootExceptionHandler {
@ExceptionHandler(JeecgBootException.class)
public Result<?> handleJeecgBootException(JeecgBootException e){
log.error(e.getMessage(), e);
return Result.error(e.getMessage());
addSysLog(e);
return Result.error(e.getErrCode(), e.getMessage());
}
/**
* 处理自定义异常
*/
@ExceptionHandler(JeecgBootBizTipException.class)
public Result<?> handleJeecgBootBizTipException(JeecgBootBizTipException e){
log.error(e.getMessage());
return Result.error(e.getErrCode(), e.getMessage());
}
/**
@ -61,6 +72,7 @@ public class JeecgBootExceptionHandler {
@ExceptionHandler(JeecgCloudException.class)
public Result<?> handleJeecgCloudException(JeecgCloudException e){
log.error(e.getMessage(), e);
addSysLog(e);
return Result.error(e.getMessage());
}
@ -71,24 +83,28 @@ public class JeecgBootExceptionHandler {
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public Result<?> handleJeecgBoot401Exception(JeecgBoot401Exception e){
log.error(e.getMessage(), e);
addSysLog(e);
return new Result(401,e.getMessage());
}
@ExceptionHandler(NoHandlerFoundException.class)
public Result<?> handlerNoFoundException(Exception e) {
log.error(e.getMessage(), e);
addSysLog(e);
return Result.error(404, "路径不存在,请检查路径是否正确");
}
@ExceptionHandler(DuplicateKeyException.class)
public Result<?> handleDuplicateKeyException(DuplicateKeyException e){
log.error(e.getMessage(), e);
addSysLog(e);
return Result.error("数据库中已存在该记录");
}
@ExceptionHandler(AccessDeniedException.class)
public Result<?> handleAuthorizationException(AccessDeniedException e){
return Result.noauth("没有权限,请联系管理员授权");
@ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
public Result<?> handleAuthorizationException(AuthorizationException e){
log.error(e.getMessage(), e);
return Result.noauth("没有权限,请联系管理员授权,后刷新缓存!");
}
@ExceptionHandler(Exception.class)
@ -101,6 +117,7 @@ public class JeecgBootExceptionHandler {
return Result.error(errorInfoEnum.getError());
}
//update-end---author:zyf ---date:20220411 for处理Sentinel限流自定义异常
addSysLog(e);
return Result.error("操作失败,"+e.getMessage());
}
@ -125,6 +142,7 @@ public class JeecgBootExceptionHandler {
}
log.error(sb.toString(), e);
//return Result.error("没有权限,请联系管理员授权");
addSysLog(e);
return Result.error(405,sb.toString());
}
@ -134,12 +152,14 @@ public class JeecgBootExceptionHandler {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public Result<?> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
log.error(e.getMessage(), e);
addSysLog(e);
return Result.error("文件大小超出10MB限制, 请压缩或降低文件质量! ");
}
@ExceptionHandler(DataIntegrityViolationException.class)
public Result<?> handleDataIntegrityViolationException(DataIntegrityViolationException e) {
log.error(e.getMessage(), e);
addSysLog(e);
//【issues/3624】数据库执行异常handleDataIntegrityViolationException提示有误 #3624
return Result.error("执行数据库异常,违反了完整性例如:违反惟一约束、违反非空限制、字段内容超出长度等");
}
@ -147,6 +167,7 @@ public class JeecgBootExceptionHandler {
@ExceptionHandler(PoolException.class)
public Result<?> handlePoolException(PoolException e) {
log.error(e.getMessage(), e);
addSysLog(e);
return Result.error("Redis 连接异常!");
}
@ -167,7 +188,57 @@ public class JeecgBootExceptionHandler {
log.error("校验失败存在SQL注入风险{}", msg);
return Result.error("校验失败存在SQL注入风险");
}
addSysLog(exception);
return Result.error("校验失败存在SQL注入风险" + msg);
}
//update-begin---author:chenrui ---date:20240423 for[QQYUN-8732]把错误的日志都抓取了 方便后续处理,单独弄个日志类型------------
/**
* 添加异常新系统日志
* @param e 异常
* @author chenrui
* @date 2024/4/22 17:16
*/
private void addSysLog(Throwable e) {
LogDTO log = new LogDTO();
log.setLogType(CommonConstant.LOG_TYPE_4);
log.setLogContent(e.getClass().getName()+":"+e.getMessage());
log.setRequestParam(ExceptionUtils.getStackTrace(e));
//获取request
HttpServletRequest request = null;
try {
request = SpringContextUtils.getHttpServletRequest();
} catch (NullPointerException | BeansException ignored) {
}
if (null != request) {
//请求的参数
Map<String, String[]> parameterMap = request.getParameterMap();
if(!CollectionUtils.isEmpty(parameterMap)){
log.setMethod(oConvertUtils.mapToString(request.getParameterMap()));
}
// 请求地址
log.setRequestUrl(request.getRequestURI());
//设置IP地址
log.setIp(IpUtils.getIpAddr(request));
//设置客户端
if(BrowserUtils.isDesktop(request)){
log.setClientType(ClientTerminalTypeEnum.PC.getKey());
}else{
log.setClientType(ClientTerminalTypeEnum.APP.getKey());
}
}
//获取登录用户信息
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
if(sysUser!=null){
log.setUserid(sysUser.getUsername());
log.setUsername(sysUser.getRealname());
}
baseCommonService.addLog(log);
}
//update-end---author:chenrui ---date:20240423 for[QQYUN-8732]把错误的日志都抓取了 方便后续处理,单独弄个日志类型------------
}

View File

@ -1,28 +0,0 @@
package org.jeecg.common.exception;
import lombok.Data;
/**
* @author kezhijie@wuhandsj.com
* @date 2024/1/2 11:38
*/
@Data
public class JeecgCaptchaException extends RuntimeException{
private Integer code;
private static final long serialVersionUID = -9093410345065209053L;
public JeecgCaptchaException(Integer code, String message) {
super(message);
this.code = code;
}
public JeecgCaptchaException(String message, Throwable cause) {
super(message, cause);
}
public JeecgCaptchaException(Throwable cause) {
super(cause);
}
}

View File

@ -1,18 +1,17 @@
package org.jeecg.common.system.base.controller;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.config.security.utils.SecureUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
@ -20,14 +19,13 @@ import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
@ -53,7 +51,7 @@ public class JeecgController<T, S extends IService<T>> {
protected ModelAndView exportXls(HttpServletRequest request, T object, Class<T> clazz, String title) {
// Step.1 组装查询条件
QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
LoginUser sysUser = SecureUtil.currentUser();
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
// 过滤选中数据
String selections = request.getParameter("selections");
@ -91,7 +89,7 @@ public class JeecgController<T, S extends IService<T>> {
protected ModelAndView exportXlsSheet(HttpServletRequest request, T object, Class<T> clazz, String title,String exportFields,Integer pageNum) {
// Step.1 组装查询条件
QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
LoginUser sysUser = SecureUtil.currentUser();
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
// Step.2 计算分页sheet数据
double total = service.count();
int count = (int)Math.ceil(total/pageNum);

View File

@ -9,10 +9,10 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* @Description: Entity基类
@ -30,20 +30,20 @@ public class JeecgEntity implements Serializable {
* ID
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "ID")
@ApiModelProperty(value = "ID")
private java.lang.String id;
/**
* 创建人
*/
@Schema(description = "创建人")
@ApiModelProperty(value = "创建人")
@Excel(name = "创建人", width = 15)
private java.lang.String createBy;
/**
* 创建时间
*/
@Schema(description = "创建时间")
@ApiModelProperty(value = "创建时间")
@Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ -52,14 +52,14 @@ public class JeecgEntity implements Serializable {
/**
* 更新人
*/
@Schema(description = "更新人")
@ApiModelProperty(value = "更新人")
@Excel(name = "更新人", width = 15)
private java.lang.String updateBy;
/**
* 更新时间
*/
@Schema(description = "更新时间")
@ApiModelProperty(value = "更新时间")
@Excel(name = "更新时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")

View File

@ -0,0 +1,19 @@
package org.jeecg.common.system.enhance;
import java.util.List;
/**
* 用户增强
*/
public interface UserFilterEnhance {
/**
* 获取用户id
* @param loginUserId 当前登录的用户id
*
* @return List<String> 返回多个用户id
*/
default List<String> getUserIds(String loginUserId) {
return null;
}
}

View File

@ -2,7 +2,6 @@ package org.jeecg.common.system.query;
import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
@ -15,7 +14,6 @@ import java.util.stream.Collectors;
import org.apache.commons.beanutils.PropertyUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.DataBaseConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.util.JeecgDataAutorUtils;
import org.jeecg.common.system.util.JwtUtil;
@ -25,7 +23,6 @@ import org.jeecg.common.util.*;
import org.springframework.util.NumberUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
@ -94,11 +91,28 @@ public class QueryGenerator {
public static <T> QueryWrapper<T> initQueryWrapper(T searchObj,Map<String, String[]> parameterMap){
long start = System.currentTimeMillis();
QueryWrapper<T> queryWrapper = new QueryWrapper<T>();
installMplus(queryWrapper, searchObj, parameterMap);
installMplus(queryWrapper, searchObj, parameterMap, null);
log.debug("---查询条件构造器初始化完成,耗时:"+(System.currentTimeMillis()-start)+"毫秒----");
return queryWrapper;
}
//update-begin---author:chenrui ---date:20240527 for[TV360X-378]增加自定义字段查询规则功能------------
/**
* 获取查询条件构造器QueryWrapper实例 通用查询条件已被封装完成
* @param searchObj 查询实体
* @param parameterMap request.getParameterMap()
* @param customRuleMap 自定义字段查询规则 {field:QueryRuleEnum}
* @return QueryWrapper实例
*/
public static <T> QueryWrapper<T> initQueryWrapper(T searchObj,Map<String, String[]> parameterMap, Map<String, QueryRuleEnum> customRuleMap){
long start = System.currentTimeMillis();
QueryWrapper<T> queryWrapper = new QueryWrapper<T>();
installMplus(queryWrapper, searchObj, parameterMap, customRuleMap);
log.debug("---查询条件构造器初始化完成,耗时:"+(System.currentTimeMillis()-start)+"毫秒----");
return queryWrapper;
}
//update-end---author:chenrui ---date:20240527 for[TV360X-378]增加自定义字段查询规则功能------------
/**
* 组装Mybatis Plus 查询条件
* <p>使用此方法 需要有如下几点注意:
@ -108,8 +122,7 @@ public class QueryGenerator {
* <br>正确示例:QueryWrapper<JeecgDemo> queryWrapper = new QueryWrapper<JeecgDemo>();
* <br>3.也可以不使用这个方法直接调用 {@link #initQueryWrapper}直接获取实例
*/
private static void installMplus(QueryWrapper<?> queryWrapper,Object searchObj,Map<String, String[]> parameterMap) {
private static void installMplus(QueryWrapper<?> queryWrapper, Object searchObj, Map<String, String[]> parameterMap, Map<String, QueryRuleEnum> customRuleMap) {
/*
* 注意:权限查询由前端配置数据规则 当一个人有多个所属部门时候 可以在规则配置包含条件 orgCode 包含 #{sys_org_code}
但是不支持在自定义SQL中写orgCode in #{sys_org_code}
@ -173,9 +186,17 @@ public class QueryGenerator {
log.info("---查询过滤器Query规则---field:{}, rule:{}, value:{}", field, "like", vals[0]);
queryWrapper.and(j -> j.like(field,vals[0]));
}
}else {
//update-begin---author:chenrui ---date:20240527 for[TV360X-378]增加自定义字段查询规则功能------------
QueryRuleEnum rule;
if(null != customRuleMap && customRuleMap.containsKey(name)) {
// 有自定义规则,使用自定义规则.
rule = customRuleMap.get(name);
}else {
//根据参数值带什么关键字符串判断走什么类型的查询
QueryRuleEnum rule = convert2Rule(value);
rule = convert2Rule(value);
}
//update-end---author:chenrui ---date:20240527 for[TV360X-378]增加自定义字段查询规则功能------------
value = replaceValue(rule,value);
// add -begin 添加判断为字符串时设为全模糊查询
//if( (rule==null || QueryRuleEnum.EQ.equals(rule)) && "class java.lang.String".equals(type)) {
@ -274,7 +295,7 @@ public class QueryGenerator {
//update-end-author:scott date:2022-10-10 for:【jeecg-boot/issues/I5FJU6】doMultiFieldsOrder() 多字段排序方法存在问题
//SQL注入check
SqlInjectionUtil.filterContent(column);
SqlInjectionUtil.filterContentMulti(column);
//update-begin--Author:scott Date:20210531 for36 多条件排序无效问题修正-------
// 排序规则修改
@ -678,9 +699,40 @@ public class QueryGenerator {
case LEFT_LIKE:
queryWrapper.likeLeft(name, value);
break;
case NOT_LEFT_LIKE:
queryWrapper.notLikeLeft(name, value);
break;
case RIGHT_LIKE:
queryWrapper.likeRight(name, value);
break;
case NOT_RIGHT_LIKE:
queryWrapper.notLikeRight(name, value);
break;
//update-begin---author:chenrui ---date:20240527 for[TV360X-378]下拉多框根据条件查询不出来:增加自定义字段查询规则功能------------
case LIKE_WITH_OR:
final String nameFinal = name;
Object[] vals;
if (value instanceof String) {
vals = value.toString().split(COMMA);
} else if (value instanceof String[]) {
vals = (Object[]) value;
}
//update-begin-author:taoyan date:20200909 for:【bug】in 类型多值查询 不适配postgresql #1671
else if (value.getClass().isArray()) {
vals = (Object[]) value;
} else {
vals = new Object[]{value};
}
queryWrapper.and(j -> {
log.info("---查询过滤器Query规则---field:{}, rule:{}, value:{}", nameFinal, "like", vals[0]);
j = j.like(nameFinal, vals[0]);
for (int k = 1; k < vals.length; k++) {
j = j.or().like(nameFinal, vals[k]);
log.info("---查询过滤器Query规则 .or()---field:{}, rule:{}, value:{}", nameFinal, "like", vals[k]);
}
});
break;
//update-end---author:chenrui ---date:20240527 for[TV360X-378]下拉多框根据条件查询不出来:增加自定义字段查询规则功能------------
default:
log.info("--查询规则未匹配到---");
break;
@ -856,7 +908,9 @@ public class QueryGenerator {
Class propType = origDescriptors[i].getPropertyType();
boolean isString = propType.equals(String.class);
Object value;
if(isString) {
//update-begin---author:chenrui ---date:20240527 for[TV360X-539]数据权限,配置日期等于条件时后端报转换错误------------
if(isString || Date.class.equals(propType)) {
//update-end---author:chenrui ---date:20240527 for[TV360X-539]数据权限,配置日期等于条件时后端报转换错误------------
value = converRuleValue(dataRule.getRuleValue());
}else {
value = NumberUtils.parseNumber(dataRule.getRuleValue(),propType);

View File

@ -33,12 +33,21 @@ public enum QueryRuleEnum {
RIGHT_LIKE("RIGHT_LIKE","right_like","右模糊"),
/**查询规则 带加号等于*/
EQ_WITH_ADD("EQWITHADD","eq_with_add","带加号等于"),
/**查询规则 多词模糊匹配*/
/**查询规则 多词模糊匹配(and)*/
LIKE_WITH_AND("LIKEWITHAND","like_with_and","多词模糊匹配————暂时未用上"),
/**查询规则 多词模糊匹配(or)*/
LIKE_WITH_OR("LIKEWITHOR","like_with_or","多词模糊匹配(or)"),
/**查询规则 自定义SQL片段*/
SQL_RULES("USE_SQL_RULES","ext","自定义SQL片段"),
/** 查询工作表 */
LINKAGE("LINKAGE","linkage","查询工作表"),
// ------- 当前表单设计器内专用 -------
/**查询规则 不以…结尾*/
NOT_LEFT_LIKE("NOT_LEFT_LIKE","not_left_like","不以…结尾"),
/**查询规则 不以…开头*/
NOT_RIGHT_LIKE("NOT_RIGHT_LIKE","not_right_like","不以…开头"),
/** 值为空 */
EMPTY("EMPTY","empty","值为空"),
/** 值不为空 */
@ -49,7 +58,10 @@ public enum QueryRuleEnum {
ELE_MATCH("ELE_MATCH","elemMatch","多词匹配"),
/**查询规则 范围查询*/
RANGE("RANGE","range","范围查询"),
NOT_RANGE("NOT_RANGE","not_range","不在范围查询");
/**查询规则 不在范围查询*/
NOT_RANGE("NOT_RANGE","not_range","不在范围查询"),
/** 自定义mongodb查询语句 */
CUSTOM_MONGODB("CUSTOM_MONGODB","custom_mongodb","自定义mongodb查询语句");
// ------- 当前表单设计器内专用 -------
private String value;

View File

@ -5,7 +5,7 @@ import org.jeecg.common.system.vo.SysUserCacheInfo;
import org.jeecg.common.util.SpringContextUtils;
import org.springframework.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

View File

@ -1,7 +1,5 @@
package org.jeecg.common.system.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
@ -12,17 +10,14 @@ import com.google.common.base.Joiner;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.util.Date;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.CommonAPI;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.DataBaseConstant;
@ -34,22 +29,6 @@ import org.jeecg.common.system.vo.SysUserCacheInfo;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.security.self.SelfAuthenticationProvider;
import org.jeecg.config.security.self.SelfAuthenticationToken;
import org.jeecg.config.security.utils.SecureUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.*;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.context.AuthorizationServerContextHolder;
import org.springframework.security.oauth2.server.authorization.token.DefaultOAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
/**
* @Author Scott
@ -63,8 +42,6 @@ public class JwtUtil {
public static final long EXPIRE_TIME = (7 * 12) * 60 * 60 * 1000;
static final String WELL_NUMBER = SymbolConstant.WELL_NUMBER + SymbolConstant.LEFT_CURLY_BRACKET;
public static final String DEFAULT_CLIENT = "jeecg-client";
/**
*
* @param response
@ -100,9 +77,10 @@ public class JwtUtil {
public static boolean verify(String token, String username, String secret) {
try {
// 根据密码生成JWT效验器
JwtDecoder jwtDecoder = SpringContextUtils.getBean(JwtDecoder.class);
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
// 效验TOKEN
jwtDecoder.decode(token);
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (Exception exception) {
return false;
@ -117,33 +95,24 @@ public class JwtUtil {
public static String getUsername(String token) {
try {
DecodedJWT jwt = JWT.decode(token);
LoginUser loginUser = JSONObject.parseObject(jwt.getClaim("sub").asString(), LoginUser.class);
return loginUser.getUsername();
return jwt.getClaim("username").asString();
} catch (JWTDecodeException e) {
return null;
}
}
/**
* 生成token
* 生成签名,5min后过期
*
* @param username 用户名
* @param secret 用户的密码
* @return 加密的token
*/
public static String sign(String username, String secret) {
Map<String, Object> additionalParameter = new HashMap<>();
additionalParameter.put("username", username);
RegisteredClientRepository registeredClientRepository = SpringContextUtils.getBean(RegisteredClientRepository.class);
SelfAuthenticationProvider selfAuthenticationProvider = SpringContextUtils.getBean(SelfAuthenticationProvider.class);
OAuth2ClientAuthenticationToken client = new OAuth2ClientAuthenticationToken(Objects.requireNonNull(registeredClientRepository.findByClientId("jeecg-client")), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, null);
client.setAuthenticated(true);
SelfAuthenticationToken selfAuthenticationToken = new SelfAuthenticationToken(client, additionalParameter);
selfAuthenticationToken.setAuthenticated(true);
OAuth2AccessTokenAuthenticationToken accessToken = (OAuth2AccessTokenAuthenticationToken) selfAuthenticationProvider.authenticate(selfAuthenticationToken);
return accessToken.getAccessToken().getTokenValue();
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(secret);
// 附带username信息
return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm);
}
@ -208,7 +177,7 @@ public class JwtUtil {
//2.通过shiro获取登录用户信息
LoginUser sysUser = null;
try {
sysUser = SecureUtil.currentUser();
sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
} catch (Exception e) {
log.warn("SecurityUtils.getSubject() 获取用户信息异常:" + e.getMessage());
}
@ -252,6 +221,16 @@ public class JwtUtil {
returnValue = user.getSysUserCode();
}
}
// 替换为系统登录用户ID
else if (key.equals(DataBaseConstant.SYS_USER_ID) || key.equalsIgnoreCase(DataBaseConstant.SYS_USER_ID_TABLE)) {
if(user==null) {
returnValue = sysUser.getId();
}else {
returnValue = user.getSysUserId();
}
}
//替换为系统登录用户真实名字
else if (key.equals(DataBaseConstant.SYS_USER_NAME)|| key.toLowerCase().equals(DataBaseConstant.SYS_USER_NAME_TABLE)) {
if(user==null) {
@ -269,6 +248,16 @@ public class JwtUtil {
returnValue = user.getSysOrgCode();
}
}
// 替换为系统用户登录所使用的机构ID
else if (key.equals(DataBaseConstant.SYS_ORG_ID) || key.equalsIgnoreCase(DataBaseConstant.SYS_ORG_ID_TABLE)) {
if (user == null) {
returnValue = sysUser.getOrgId();
} else {
returnValue = user.getSysOrgId();
}
}
//替换为系统用户所拥有的所有机构编码
else if (key.equals(DataBaseConstant.SYS_MULTI_ORG_CODE)|| key.toLowerCase().equals(DataBaseConstant.SYS_MULTI_ORG_CODE_TABLE)) {
if(user==null){
@ -282,6 +271,16 @@ public class JwtUtil {
}
}
}
// 替换为当前登录用户的角色code多个逗号分割
else if (key.equals(DataBaseConstant.SYS_ROLE_CODE) || key.equalsIgnoreCase(DataBaseConstant.SYS_ROLE_CODE_TABLE)) {
if (user == null) {
returnValue = sysUser.getRoleCode();
} else {
returnValue = user.getSysRoleCode();
}
}
//update-begin-author:taoyan date:20210330 for:多租户ID作为系统变量
else if (key.equals(TenantConstant.TENANT_ID) || key.toLowerCase().equals(TenantConstant.TENANT_ID_TABLE)){
try {

View File

@ -3,7 +3,9 @@ package org.jeecg.common.system.util;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.annotation.EnumDict;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
@ -114,4 +116,21 @@ public class ResourceUtil {
return map;
}
/**
* 获取实现类
*
* @param classPath
*/
public static Object getImplementationClass(String classPath){
try {
Class<?> aClass = Class.forName(classPath);
return SpringContextUtils.getBean(aClass);
} catch (ClassNotFoundException e) {
log.error("类没有找到",e);
return null;
} catch (NoSuchBeanDefinitionException e){
log.error(classPath + "没有实现",e);
return null;
}
}
}

View File

@ -1,18 +1,13 @@
package org.jeecg.common.system.vo;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.jeecg.common.desensitization.annotation.SensitiveField;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
/**
* <p>
@ -25,10 +20,8 @@ import java.util.Set;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class LoginUser implements Serializable {
public class LoginUser {
private static final long serialVersionUID = -7143159031677245866L;
/**
* 登录人id
*/
@ -58,6 +51,17 @@ public class LoginUser implements Serializable {
*/
@SensitiveField
private String orgCode;
/**
* 当前登录部门id
*/
@SensitiveField
private String orgId;
/**
* 当前登录角色code多个逗号分割
*/
@SensitiveField
private String roleCode;
/**
* 头像
*/
@ -134,29 +138,4 @@ public class LoginUser implements Serializable {
/**设备id uniapp推送用*/
private String clientId;
@SensitiveField
private String salt;
@Override
public String toString() {
// 重新构建对象过滤一些敏感字段
LoginUser loginUser = new LoginUser();
loginUser.setId(id);
loginUser.setUsername(username);
loginUser.setRealname(realname);
loginUser.setOrgCode(orgCode);
loginUser.setSex(sex);
loginUser.setEmail(email);
loginUser.setPhone(phone);
loginUser.setDelFlag(delFlag);
loginUser.setStatus(status);
loginUser.setActivitiSync(activitiSync);
loginUser.setUserIdentity(userIdentity);
loginUser.setDepartIds(departIds);
loginUser.setPost(post);
loginUser.setTelephone(telephone);
loginUser.setRelTenantIds(relTenantIds);
loginUser.setClientId(clientId);
return JSON.toJSONString(loginUser);
}
}

View File

@ -19,6 +19,8 @@ public class SysFilesModel {
private String storeType;
/**文件大小kb*/
private Double fileSize;
/**租户id*/
private String tenantId;
public String getId() {
return id;
@ -67,4 +69,12 @@ public class SysFilesModel {
public void setFileSize(Double fileSize) {
this.fileSize = fileSize;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
}

View File

@ -10,16 +10,28 @@ import org.jeecg.common.util.DateUtils;
*/
public class SysUserCacheInfo {
private String sysUserId;
private String sysUserCode;
private String sysUserName;
private String sysOrgCode;
/**
* 当前用户部门ID
*/
private String sysOrgId;
private List<String> sysMultiOrgCode;
private boolean oneDepart;
/**
* 当前用户角色code多个逗号分割
*/
private String sysRoleCode;
public boolean isOneDepart() {
return oneDepart;
}
@ -68,4 +80,27 @@ public class SysUserCacheInfo {
this.sysMultiOrgCode = sysMultiOrgCode;
}
public String getSysUserId() {
return sysUserId;
}
public void setSysUserId(String sysUserId) {
this.sysUserId = sysUserId;
}
public String getSysOrgId() {
return sysOrgId;
}
public void setSysOrgId(String sysOrgId) {
this.sysOrgId = sysOrgId;
}
public String getSysRoleCode() {
return sysRoleCode;
}
public void setSysRoleCode(String sysRoleCode) {
this.sysRoleCode = sysRoleCode;
}
}

View File

@ -5,7 +5,7 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jakarta.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest;
/**
*

View File

@ -19,7 +19,7 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.io.ByteArrayInputStream;
import java.io.File;
@ -28,7 +28,9 @@ import java.io.InputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -302,7 +304,7 @@ public class CommonUtils {
DB_TYPE = DataBaseConstant.DB_TYPE_ORACLE;
}else if(dbType.indexOf(DataBaseConstant.DB_TYPE_SQLSERVER)>=0||dbType.indexOf(sqlserver)>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_SQLSERVER;
}else if(dbType.indexOf(DataBaseConstant.DB_TYPE_POSTGRESQL)>=0) {
}else if(dbType.indexOf(DataBaseConstant.DB_TYPE_POSTGRESQL)>=0 || dbType.indexOf(DataBaseConstant.DB_TYPE_KINGBASEES)>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_POSTGRESQL;
}else if(dbType.indexOf(DataBaseConstant.DB_TYPE_MARIADB)>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_MARIADB;
@ -346,8 +348,11 @@ public class CommonUtils {
//返回 host domain
String baseDomainPath = null;
int length = 80;
if(length == serverPort){
//update-begin---author:wangshuai---date:2024-03-15---for:【QQYUN-8561】企业微信登陆请求接口设置上下文不一致导致接口404---
int httpPort = 80;
int httpsPort = 443;
if(httpPort == serverPort || httpsPort == serverPort){
//update-end---author:wangshuai---date:2024-03-15---for:【QQYUN-8561】企业微信登陆请求接口设置上下文不一致导致接口404---~
baseDomainPath = scheme + "://" + serverName + contextPath ;
}else{
baseDomainPath = scheme + "://" + serverName + ":" + serverPort + contextPath ;
@ -467,4 +472,19 @@ public class CommonUtils {
}
return false;
}
/**
* 输出info日志会捕获异常防止因为日志问题导致程序异常
*
* @param msg
* @param objects
*/
public static void logInfo(String msg, Object... objects) {
try {
log.info(msg, objects);
} catch (Exception e) {
log.warn("{} —— {}", msg, e.getMessage());
}
}
}

View File

@ -0,0 +1,242 @@
package org.jeecg.common.util;
import cn.hutool.core.date.DateUtil;
import org.jeecg.common.constant.enums.DateRangeEnum;
import java.util.Calendar;
import java.util.Date;
/**
* 日期范围工具类
*
* @author scott
* @date 20230801
*/
public class DateRangeUtils {
/**
* 根据日期范围枚举获取日期范围
*
* @param rangeEnum
* @return Date[]
*/
public static Date[] getDateRangeByEnum(DateRangeEnum rangeEnum) {
if (rangeEnum == null) {
return null;
}
Date[] ranges = new Date[2];
switch (rangeEnum) {
case TODAY:
ranges[0] = getTodayStartTime();
ranges[1] = getTodayEndTime();
break;
case YESTERDAY:
ranges[0] = getYesterdayStartTime();
ranges[1] = getYesterdayEndTime();
break;
case TOMORROW:
ranges[0] = getTomorrowStartTime();
ranges[1] = getTomorrowEndTime();
break;
case THIS_WEEK:
ranges[0] = getThisWeekStartDay();
ranges[1] = getThisWeekEndDay();
break;
case LAST_WEEK:
ranges[0] = getLastWeekStartDay();
ranges[1] = getLastWeekEndDay();
break;
case NEXT_WEEK:
ranges[0] = getNextWeekStartDay();
ranges[1] = getNextWeekEndDay();
break;
case LAST_7_DAYS:
ranges[0] = getLast7DaysStartTime();
ranges[1] = getLast7DaysEndTime();
break;
case THIS_MONTH:
ranges[0] = getThisMonthStartDay();
ranges[1] = getThisMonthEndDay();
break;
case LAST_MONTH:
ranges[0] = getLastMonthStartDay();
ranges[1] = getLastMonthEndDay();
break;
case NEXT_MONTH:
ranges[0] = getNextMonthStartDay();
ranges[1] = getNextMonthEndDay();
break;
default:
return null;
}
return ranges;
}
/**
* 获得下月第一天 周日 00:00:00
*/
public static Date getNextMonthStartDay() {
return DateUtil.beginOfMonth(DateUtil.nextMonth());
}
/**
* 获得下月最后一天 23:59:59
*/
public static Date getNextMonthEndDay() {
return DateUtil.endOfMonth(DateUtil.nextMonth());
}
/**
* 获得本月第一天 周日 00:00:00
*/
public static Date getThisMonthStartDay() {
return DateUtil.beginOfMonth(DateUtil.date());
}
/**
* 获得本月最后一天 23:59:59
*/
public static Date getThisMonthEndDay() {
return DateUtil.endOfMonth(DateUtil.date());
}
/**
* 获得上月第一天 周日 00:00:00
*/
public static Date getLastMonthStartDay() {
return DateUtil.beginOfMonth(DateUtil.lastMonth());
}
/**
* 获得上月最后一天 23:59:59
*/
public static Date getLastMonthEndDay() {
return DateUtil.endOfMonth(DateUtil.lastMonth());
}
/**
* 获得上周第一天 周一 00:00:00
*/
public static Date getLastWeekStartDay() {
return DateUtil.beginOfWeek(DateUtil.lastWeek());
}
/**
* 获得上周最后一天 周日 23:59:59
*/
public static Date getLastWeekEndDay() {
return DateUtil.endOfWeek(DateUtil.lastWeek());
}
/**
* 获得本周第一天 周一 00:00:00
*/
public static Date getThisWeekStartDay() {
Date today = new Date();
return DateUtil.beginOfWeek(today);
}
/**
* 获得本周最后一天 周日 23:59:59
*/
public static Date getThisWeekEndDay() {
Date today = new Date();
return DateUtil.endOfWeek(today);
}
/**
* 获得下周第一天 周一 00:00:00
*/
public static Date getNextWeekStartDay() {
return DateUtil.beginOfWeek(DateUtil.nextWeek());
}
/**
* 获得下周最后一天 周日 23:59:59
*/
public static Date getNextWeekEndDay() {
return DateUtil.endOfWeek(DateUtil.nextWeek());
}
/**
* 过去七天开始时间(不含今天)
*
* @return
*/
public static Date getLast7DaysStartTime() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, -7);
return DateUtil.beginOfDay(calendar.getTime());
}
/**
* 过去七天结束时间(不含今天)
*
* @return
*/
public static Date getLast7DaysEndTime() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(getLast7DaysStartTime());
calendar.add(Calendar.DATE, 6);
return DateUtil.endOfDay(calendar.getTime());
}
/**
* 昨天开始时间
*
* @return
*/
public static Date getYesterdayStartTime() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, -1);
return DateUtil.beginOfDay(calendar.getTime());
}
/**
* 昨天结束时间
*
* @return
*/
public static Date getYesterdayEndTime() {
return DateUtil.endOfDay(getYesterdayStartTime());
}
/**
* 明天开始时间
*
* @return
*/
public static Date getTomorrowStartTime() {
return DateUtil.beginOfDay(DateUtil.tomorrow());
}
/**
* 明天结束时间
*
* @return
*/
public static Date getTomorrowEndTime() {
return DateUtil.endOfDay(DateUtil.tomorrow());
}
/**
* 今天开始时间
*
* @return
*/
public static Date getTodayStartTime() {
return DateUtil.beginOfDay(new Date());
}
/**
* 今天结束时间
*
* @return
*/
public static Date getTodayEndTime() {
return DateUtil.endOfDay(new Date());
}
}

View File

@ -8,6 +8,11 @@ import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
@ -117,6 +122,17 @@ public class DateUtils extends PropertyEditorSupport {
return new Date();
}
/**
* 当前日期
*
* @return 系统当前日期(不带时分秒)
*/
public static LocalDate getLocalDate() {
LocalDate today = LocalDate.now();
return today;
}
/**
* 指定毫秒数表示的日期
*
@ -704,6 +720,44 @@ public class DateUtils extends PropertyEditorSupport {
return isSameMonth && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
}
/**
* 计算与当前日期的时间差
*
* @param targetDate
* @return
*/
public static long calculateTimeDifference(Date targetDate) {
// 获取当前时间
LocalDateTime currentTime = LocalDateTime.now();
// 将java.util.Date转换为java.time.LocalDateTime
LocalDateTime convertedTargetDate = targetDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
// 计算时间差
Duration duration = Duration.between(currentTime, convertedTargetDate);
// 获取时间差的毫秒数
long timeDifferenceInMillis = duration.toMillis();
return timeDifferenceInMillis;
}
/**
* 计算与当前日期的日期天数差
*
* @param targetDate
* @return
*/
public static long calculateDaysDifference(Date targetDate) {
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 将java.util.Date转换为java.time.LocalDate
LocalDate convertedTargetDate = targetDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// 计算日期差
long daysDifference = ChronoUnit.DAYS.between(currentDate, convertedTargetDate);
return daysDifference;
}
/**
* 判断两个时间是否是同一周
*

View File

@ -62,8 +62,8 @@ public class DySmsHelper {
//update-begin-authortaoyan date:20200811 for:配置类数据获取
StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class);
logger.info("阿里大鱼短信秘钥 accessKeyId" + staticConfig.getAccessKeyId());
logger.info("阿里大鱼短信秘钥 accessKeySecret"+ staticConfig.getAccessKeySecret());
//logger.info("阿里大鱼短信秘钥 accessKeyId" + staticConfig.getAccessKeyId());
//logger.info("阿里大鱼短信秘钥 accessKeySecret"+ staticConfig.getAccessKeySecret());
setAccessKeyId(staticConfig.getAccessKeyId());
setAccessKeySecret(staticConfig.getAccessKeySecret());
//update-end-authortaoyan date:20200811 for:配置类数据获取

View File

@ -0,0 +1,96 @@
package org.jeecg.common.util;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ConcurrentHashMap;
/**
* 防止刷短信接口只针对绑定手机号模板SMS_175430166
*
* 1、同一IP1分钟内发短信不允许超过5次每一分钟重置每个IP请求次数
* 2、同一IP1分钟内发短信超过20次进入黑名单不让使用短信接口
*
* 3、短信接口加签和时间戳
* 涉及接口:
* /sys/sms
* /desform/api/sendVerifyCode
* /sys/sendChangePwdSms
*/
@Slf4j
public class DySmsLimit {
// 1分钟内最大发短信数量单一IP
private static final int MAX_MESSAGE_PER_MINUTE = 5;
// 1分钟
private static final int MILLIS_PER_MINUTE = 60000;
// 一分钟内报警线最大短信数量超了进黑名单单一IP
private static final int MAX_TOTAL_MESSAGE_PER_MINUTE = 20;
private static ConcurrentHashMap<String, Long> ipLastRequestTime = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, Integer> ipRequestCount = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, Boolean> ipBlacklist = new ConcurrentHashMap<>();
/**
* @param ip 请求发短信的IP地址
* @return
*/
public static boolean canSendSms(String ip) {
long currentTime = System.currentTimeMillis();
long lastRequestTime = ipLastRequestTime.getOrDefault(ip, 0L);
int requestCount = ipRequestCount.getOrDefault(ip, 0);
log.info("IP{}, Msg requestCount{} ", ip, requestCount);
if (ipBlacklist.getOrDefault(ip, false)) {
// 如果IP在黑名单中则禁止发送短信
log.error("IP{}, 进入黑名单,禁止发送请求短信!", ip);
return false;
}
if (currentTime - lastRequestTime >= MILLIS_PER_MINUTE) {
// 如果距离上次请求已经超过一分钟,则重置计数
ipRequestCount.put(ip, 1);
ipLastRequestTime.put(ip, currentTime);
return true;
} else {
// 如果距离上次请求不到一分钟
ipRequestCount.put(ip, requestCount + 1);
if (requestCount < MAX_MESSAGE_PER_MINUTE) {
// 如果请求次数小于5次允许发送短信
return true;
} else if (requestCount >= MAX_TOTAL_MESSAGE_PER_MINUTE) {
// 如果请求次数超过报警线短信数量将IP加入黑名单
ipBlacklist.put(ip, true);
return false;
} else {
log.error("IP{}, 1分钟内请求短信超过5次请稍后重试", ip);
return false;
}
}
}
/**
* 图片二维码验证成功之后清空数量
*
* @param ip IP地址
*/
public static void clearSendSmsCount(String ip) {
long currentTime = System.currentTimeMillis();
ipRequestCount.put(ip, 0);
ipLastRequestTime.put(ip, currentTime);
}
// public static void main(String[] args) {
// String ip = "192.168.1.1";
// for (int i = 1; i < 50; i++) {
// if (canSendSms(ip)) {
// System.out.println("Send SMS successfully");
// } else {
// //System.out.println("Exceed SMS limit for IP " + ip);
// }
// }
//
// System.out.println(ipLastRequestTime);
// System.out.println(ipRequestCount);
// System.out.println(ipBlacklist);
// }
}

View File

@ -1,12 +1,17 @@
package org.jeecg.common.util;
import jakarta.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* IP地址
*
@ -46,14 +51,51 @@ public class IpUtils {
logger.error("IPUtils ERROR ", e);
}
// //使用代理则获取第一个IP地址
// if(StringUtils.isEmpty(ip) && ip.length() > 15) {
// if(ip.indexOf(",") > 0) {
//logger.info("获取客户端 ip{} ", ip);
// 使用代理则获取第一个IP地址
if (StringUtils.isNotEmpty(ip) && ip.length() > 15) {
if (ip.indexOf(",") > 0) {
//ip = ip.substring(0, ip.indexOf(","));
// }
// }
String[] ipAddresses = ip.split(",");
for (String ipAddress : ipAddresses) {
ipAddress = ipAddress.trim();
if (isValidIpAddress(ipAddress)) {
return ipAddress;
}
}
}
}
return ip;
}
/**
* 判断是否是IP格式
* @param ipAddress
* @return
*/
public static boolean isValidIpAddress(String ipAddress) {
String ipPattern = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
Pattern pattern = Pattern.compile(ipPattern);
Matcher matcher = pattern.matcher(ipAddress);
return matcher.matches();
}
/**
* 获取服务器上的ip
* @return
*/
public static String getServerIp(){
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getLocalHost();
String ipAddress = inetAddress.getHostAddress();
//System.out.println("IP地址: " + ipAddress);
return ipAddress;
} catch (UnknownHostException e) {
logger.error("获取ip地址失败", e);
}
return "";
}
}

View File

@ -1,7 +1,7 @@
package org.jeecg.common.util;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.ServiceNameConstants;

View File

@ -29,6 +29,17 @@ public class SqlInjectionUtil {
* 字典专用—sql注入关键词
*/
private static String specialDictSqlXssStr = "exec |peformance_schema|information_schema|extractvalue|updatexml|geohash|gtid_subset|gtid_subtract|insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |;|+|--";
/**
* 完整匹配的key不需要考虑前空格
*/
private static List<String> FULL_MATCHING_KEYWRODS = new ArrayList<>();
static {
FULL_MATCHING_KEYWRODS.add(";");
FULL_MATCHING_KEYWRODS.add("+");
FULL_MATCHING_KEYWRODS.add("--");
}
/**
* sql注入风险的 正则关键字
*
@ -50,6 +61,8 @@ public class SqlInjectionUtil {
* sql注释的正则
*/
private final static Pattern SQL_ANNOTATION = Pattern.compile("/\\*[\\s\\S]*\\*/");
private final static String SQL_ANNOTATION2 = "--";
/**
* sql注入提示语
*/
@ -62,7 +75,7 @@ public class SqlInjectionUtil {
* sql注入过滤处理遇到注入关键字抛异常
* @param values
*/
public static void filterContent(String... values) {
public static void filterContentMulti(String... values) {
filterContent(values, null);
}
@ -128,7 +141,13 @@ public class SqlInjectionUtil {
if (sql.startsWith(keyword.trim())) {
return true;
} else if (sql.contains(keyword)) {
if (sql.contains(" " + keyword)) {
// 需要匹配的sql注入关键词
String matchingText = " " + keyword;
if(FULL_MATCHING_KEYWRODS.contains(keyword)){
matchingText = keyword;
}
if (sql.contains(matchingText)) {
return true;
} else {
String regularStr = "\\s+\\S+" + keyword;
@ -244,6 +263,13 @@ public class SqlInjectionUtil {
* @return
*/
public static void checkSqlAnnotation(String str){
if(str.contains(SQL_ANNOTATION2)){
String error = "请注意SQL中不允许含注释有安全风险";
log.error(error);
throw new RuntimeException(error);
}
Matcher matcher = SQL_ANNOTATION.matcher(str);
if(matcher.find()){
String error = "请注意值可能存在SQL注入风险---> \\*.*\\";
@ -260,12 +286,20 @@ public class SqlInjectionUtil {
*
* @param table
*/
private static Pattern tableNamePattern = Pattern.compile("^[a-zA-Z][a-zA-Z0-9_]{0,63}$");
private static Pattern tableNamePattern = Pattern.compile("^[a-zA-Z][a-zA-Z0-9_\\$]{0,63}$");
public static String getSqlInjectTableName(String table) {
if(oConvertUtils.isEmpty(table)){
return table;
}
//update-begin---author:scott ---date:2024-05-28 for表单设计器列表翻译存在表名带条件导致翻译出问题----
int index = table.toLowerCase().indexOf(" where ");
if (index != -1) {
table = table.substring(0, index);
log.info("截掉where之后的新表名" + table);
}
//update-end---author:scott ---date::2024-05-28 for表单设计器列表翻译存在表名带条件导致翻译出问题----
table = table.trim();
/**
* 检验表名是否合法
@ -282,7 +316,7 @@ public class SqlInjectionUtil {
}
//进一步验证是否存在SQL注入风险
filterContent(table);
filterContentMulti(table);
return table;
}
@ -319,7 +353,7 @@ public class SqlInjectionUtil {
}
//进一步验证是否存在SQL注入风险
filterContent(field);
filterContentMulti(field);
return field;
}

View File

@ -11,13 +11,7 @@ import org.jeecg.common.exception.JeecgBoot401Exception;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import org.jeecg.config.security.JeecgRedisOAuth2AuthorizationService;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
/**
* @Author scott
@ -34,6 +28,10 @@ public class TokenUtils {
* @return
*/
public static String getTokenByRequest(HttpServletRequest request) {
if (request == null) {
return null;
}
String token = request.getParameter("token");
if (token == null) {
token = request.getHeader("X-Access-Token");
@ -118,7 +116,7 @@ public class TokenUtils {
throw new JeecgBoot401Exception("账号已被锁定,请联系管理员!");
}
// 校验token是否超时失效 & 或者账号密码是否错误
if (!jwtTokenRefresh(token, username, user.getPassword())) {
if (!jwtTokenRefresh(token, username, user.getPassword(), redisUtil)) {
throw new JeecgBoot401Exception(CommonConstant.TOKEN_IS_INVALID_MSG);
}
return true;
@ -147,15 +145,6 @@ public class TokenUtils {
return false;
}
private static boolean jwtTokenRefresh(String token, String userName, String passWord) {
JeecgRedisOAuth2AuthorizationService authRedis = SpringContextUtils.getBean(JeecgRedisOAuth2AuthorizationService.class);
OAuth2Authorization authorization = authRedis.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (Objects.nonNull(authorization) && JwtUtil.verify(token, userName, passWord)) {
return true;
}
return false;
}
/**
* 获取登录用户
*

View File

@ -38,6 +38,11 @@ public class DynamicDBUtil {
String driverClassName = dbSource.getDbDriver();
String url = dbSource.getDbUrl();
// url配置成 “123” 会触发Druid死循环一直去重复尝试连接
if (oConvertUtils.isEmpty(url) || !url.toLowerCase().startsWith("jdbc:")) {
throw new JeecgBootException("数据源URL配置格式不正确");
}
String dbUser = dbSource.getDbUsername();
String dbPassword = dbSource.getDbPassword();
dataSource.setDriverClassName(driverClassName);
@ -47,6 +52,8 @@ public class DynamicDBUtil {
dataSource.setTestOnBorrow(false);
dataSource.setTestOnReturn(false);
dataSource.setBreakAfterAcquireFailure(true);
//设置超时时间60秒
dataSource.setLoginTimeout(60);
dataSource.setConnectionErrorRetryAttempts(0);
dataSource.setUsername(dbUser);
dataSource.setMaxWait(30000);

View File

@ -1,9 +1,10 @@
package org.jeecg.common.util.encryption;
import org.apache.shiro.codec.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
/**
* @Description: AES 加密
@ -48,7 +49,7 @@ public class AesEncryptUtil {
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return Base64.getEncoder().encodeToString(encrypted);
return Base64.encodeToString(encrypted);
} catch (Exception e) {
e.printStackTrace();
@ -66,7 +67,7 @@ public class AesEncryptUtil {
*/
public static String desEncrypt(String data, String key, String iv) throws Exception {
//update-begin-author:taoyan date:2022-5-23 for:VUEN-1084 【vue3】online表单测试发现的新问题 6、解密报错 ---解码失败应该把异常抛出去,在外面处理
byte[] encrypted1 = Base64.getDecoder().decode(data);
byte[] encrypted1 = Base64.decode(data);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");

View File

@ -61,6 +61,10 @@ public class SsrfFileTypeFilter {
FILE_TYPE_WHITE_LIST.add("7z");
FILE_TYPE_WHITE_LIST.add("tar");
//app文件后缀
FILE_TYPE_WHITE_LIST.add("apk");
FILE_TYPE_WHITE_LIST.add("wgt");
//设置禁止文件的头部标记
FILE_TYPE_MAP.put("3c25402070616765206c", "jsp");
FILE_TYPE_MAP.put("3c3f7068700a0a2f2a2a0a202a205048", "php");

View File

@ -2,22 +2,21 @@ package org.jeecg.common.util;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.springframework.beans.BeanUtils;
import jakarta.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.net.*;
import java.sql.Date;
import java.util.*;
import java.util.regex.Matcher;
@ -50,6 +49,27 @@ public class oConvertUtils {
return (false);
}
/**
* 返回decode解密字符串
*
* @param inStr
* @return
*/
public static String decodeString(String inStr) {
if (oConvertUtils.isEmpty(inStr)) {
return null;
}
try {
inStr = URLDecoder.decode(inStr, "UTF-8");
} catch (Exception e) {
// 解决URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "自动"
//e.printStackTrace();
}
return inStr;
}
public static String decode(String strIn, String sourceCode, String targetCode) {
String temp = code2code(strIn, sourceCode, targetCode);
return temp;
@ -238,6 +258,20 @@ public class oConvertUtils {
return (String.valueOf(i));
}
/**
* 返回常规字符串(只保留字符串中的数字、字母、中文)
*
* @param input
* @return
*/
public static String getNormalString(String input) {
if (oConvertUtils.isEmpty(input)) {
return null;
}
String result = input.replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5]", "");
return result;
}
public static String getString(String s, String defval) {
if (isEmpty(s)) {
return (defval);
@ -287,6 +321,22 @@ public class oConvertUtils {
return (clazz.equals(String.class) || clazz.equals(Integer.class) || clazz.equals(Byte.class) || clazz.equals(Long.class) || clazz.equals(Double.class) || clazz.equals(Float.class) || clazz.equals(Character.class) || clazz.equals(Short.class) || clazz.equals(BigDecimal.class) || clazz.equals(BigInteger.class) || clazz.equals(Boolean.class) || clazz.equals(Date.class) || clazz.isPrimitive());
}
/**
* 解码base64
*
* @param base64Str base64字符串
* @return 被加密后的字符串
*/
public static String decodeBase64Str(String base64Str) {
byte[] byteContent = Base64.decodeBase64(base64Str);
if (byteContent == null) {
return null;
}
String decodedString = new String(byteContent);
return decodedString;
}
/**
* @param request
* IP
@ -413,7 +463,7 @@ public class oConvertUtils {
return false;
}
String[] childs = (String[]) childArray.toArray();
String[] childs = childArray.toArray(new String[]{});
for (String v : childs) {
if (!isIn(v, all)) {
return false;
@ -751,6 +801,16 @@ public class oConvertUtils {
return obj.getClass().isArray();
}
/**
* 获取集合的大小
*
* @param collection
* @return
*/
public static int getCollectionSize(Collection<?> collection) {
return collection != null ? collection.size() : 0;
}
/**
* 判断两个数组是否相等(数组元素不分顺序)
*
@ -942,4 +1002,31 @@ public class oConvertUtils {
return count;
}
/**
* map转str
*
* @param map
* @return
*/
public static String mapToString(Map<String, String[]> map) {
if (map == null || map.size() == 0) {
return null;
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String[]> entry : map.entrySet()) {
String key = entry.getKey();
String[] values = entry.getValue();
sb.append(key).append("=");
sb.append(values != null ? StringUtils.join(values, ",") : "");
sb.append("&");
}
String result = sb.toString();
if (result.endsWith("&")) {
result = result.substring(0, sb.length() - 1);
}
return result;
}
}

View File

@ -1,55 +1,6 @@
package org.jeecg.common.util.sqlInjection.parse;
import net.sf.jsqlparser.expression.AllValue;
import net.sf.jsqlparser.expression.AnalyticExpression;
import net.sf.jsqlparser.expression.AnyComparisonExpression;
import net.sf.jsqlparser.expression.ArrayConstructor;
import net.sf.jsqlparser.expression.ArrayExpression;
import net.sf.jsqlparser.expression.BinaryExpression;
import net.sf.jsqlparser.expression.CaseExpression;
import net.sf.jsqlparser.expression.CastExpression;
import net.sf.jsqlparser.expression.CollateExpression;
import net.sf.jsqlparser.expression.ConnectByRootOperator;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import net.sf.jsqlparser.expression.DateValue;
import net.sf.jsqlparser.expression.DoubleValue;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.ExpressionVisitor;
import net.sf.jsqlparser.expression.ExtractExpression;
import net.sf.jsqlparser.expression.Function;
import net.sf.jsqlparser.expression.HexValue;
import net.sf.jsqlparser.expression.IntervalExpression;
import net.sf.jsqlparser.expression.JdbcNamedParameter;
import net.sf.jsqlparser.expression.JdbcParameter;
import net.sf.jsqlparser.expression.JsonAggregateFunction;
import net.sf.jsqlparser.expression.JsonExpression;
import net.sf.jsqlparser.expression.JsonFunction;
import net.sf.jsqlparser.expression.JsonFunctionExpression;
import net.sf.jsqlparser.expression.KeepExpression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.MySQLGroupConcat;
import net.sf.jsqlparser.expression.NextValExpression;
import net.sf.jsqlparser.expression.NotExpression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.NumericBind;
import net.sf.jsqlparser.expression.OracleHierarchicalExpression;
import net.sf.jsqlparser.expression.OracleHint;
import net.sf.jsqlparser.expression.OracleNamedFunctionParameter;
import net.sf.jsqlparser.expression.Parenthesis;
import net.sf.jsqlparser.expression.RowConstructor;
import net.sf.jsqlparser.expression.RowGetExpression;
import net.sf.jsqlparser.expression.SignedExpression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.TimeKeyExpression;
import net.sf.jsqlparser.expression.TimeValue;
import net.sf.jsqlparser.expression.TimestampValue;
import net.sf.jsqlparser.expression.TimezoneExpression;
import net.sf.jsqlparser.expression.TryCastExpression;
import net.sf.jsqlparser.expression.UserVariable;
import net.sf.jsqlparser.expression.ValueListExpression;
import net.sf.jsqlparser.expression.VariableAssignment;
import net.sf.jsqlparser.expression.WhenClause;
import net.sf.jsqlparser.expression.XMLSerializeExpr;
import net.sf.jsqlparser.expression.*;
import net.sf.jsqlparser.expression.operators.arithmetic.Addition;
import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseAnd;
import net.sf.jsqlparser.expression.operators.arithmetic.BitwiseLeftShift;
@ -215,6 +166,23 @@ public class ConstAnalyzer implements ExpressionVisitor, ItemsListVisitor {
expr.getBetweenExpressionEnd().accept(this);
}
/**
* 用于处理 OverlapsCondition 类型的表达式
* @param overlapsCondition
*/
@Override
public void visit(OverlapsCondition overlapsCondition) {
constFlag.set(false);
}
/**
* 用于处理 SafeCastExpression 类型的表达式。
* @param safeCastExpression
*/
@Override
public void visit(SafeCastExpression safeCastExpression) {
constFlag.set(false);
}
@Override
public void visit(EqualsTo expr) {
visitBinaryExpression(expr);

View File

@ -3,7 +3,7 @@ package org.jeecg.config;
import java.util.ArrayList;
import java.util.List;
import jakarta.annotation.Resource;
import javax.annotation.Resource;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.system.vo.DictModel;

View File

@ -2,9 +2,7 @@ package org.jeecg.config;
import java.io.IOException;
import com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceAutoConfigure;
import com.alibaba.druid.spring.boot3.autoconfigure.properties.DruidStatProperties;
import jakarta.servlet.*;
import javax.servlet.*;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@ -13,6 +11,8 @@ import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
/**

View File

@ -12,7 +12,9 @@ import java.util.HashMap;
import java.util.Map;
/**
* @author eightmonth@qq.com
* 启动程序修改DruidWallConfig配置
* 允许SELECT语句的WHERE子句是一个永真条件
* @author eightmonth
* @date 2024/4/8 11:37
*/
public class DruidWallConfigRegister implements SpringApplicationRunListener {

View File

@ -32,6 +32,10 @@ public class JeecgBaseConfig {
*/
private Firewall firewall;
/**
* shiro拦截排除
*/
private Shiro shiro;
/**
* 上传文件配置
*/
@ -84,6 +88,14 @@ public class JeecgBaseConfig {
this.signatureSecret = signatureSecret;
}
public Shiro getShiro() {
return shiro;
}
public void setShiro(Shiro shiro) {
this.shiro = shiro;
}
public Path getPath() {
return path;
}

View File

@ -1,183 +1,179 @@
//package org.jeecg.config;
//
// 已使用swagger3config平替
//import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
//import io.swagger.annotations.ApiOperation;
//import org.jeecg.common.constant.CommonConstant;
//import org.springframework.beans.BeansException;
//import org.springframework.beans.factory.config.BeanPostProcessor;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.Import;
//import org.springframework.util.ReflectionUtils;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
//import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
//import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
//import springfox.documentation.builders.ApiInfoBuilder;
//import springfox.documentation.builders.ParameterBuilder;
//import springfox.documentation.builders.PathSelectors;
//import springfox.documentation.builders.RequestHandlerSelectors;
//import springfox.documentation.oas.annotations.EnableOpenApi;
//import springfox.documentation.schema.ModelRef;
//import springfox.documentation.service.*;
//import springfox.documentation.spi.DocumentationType;
//import springfox.documentation.spi.service.contexts.SecurityContext;
//import springfox.documentation.spring.web.plugins.Docket;
//import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
//import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
//import springfox.documentation.swagger2.annotations.EnableSwagger2;
//
//import java.lang.reflect.Field;
//import java.util.ArrayList;
//import java.util.Collections;
//import java.util.List;
//import java.util.stream.Collectors;
//
///**
// * @Author scott
// */
//@Configuration
//@EnableSwagger2 //开启 Swagger2
//@EnableKnife4j //开启 knife4j可以不写
//@Import(BeanValidatorPluginsConfiguration.class)
//public class Swagger2Config implements WebMvcConfigurer {
//
// /**
// *
// * 显示swagger-ui.html文档展示页还必须注入swagger资源
// *
// * @param registry
// */
// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
// registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
// registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
// }
//
// /**
// * swagger2的配置文件这里可以配置swagger2的一些基本的内容比如扫描的包等等
// *
// * @return Docket
// */
// @Bean(value = "defaultApi2")
// public Docket defaultApi2() {
// return new Docket(DocumentationType.SWAGGER_2)
// .apiInfo(apiInfo())
// .select()
// //此包路径下的类,才生成接口文档
// .apis(RequestHandlerSelectors.basePackage("org.jeecg"))
// //加了ApiOperation注解的类才生成接口文档
// .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// .paths(PathSelectors.any())
// .build()
// .securitySchemes(Collections.singletonList(securityScheme()))
// .securityContexts(securityContexts())
// .globalOperationParameters(setHeaderToken());
// }
//
// /***
// * oauth2配置
// * 需要增加swagger授权回调地址
// * http://localhost:8888/webjars/springfox-swagger-ui/o2c.html
// * @return
// */
// @Bean
// SecurityScheme securityScheme() {
// return new ApiKey(CommonConstant.X_ACCESS_TOKEN, CommonConstant.X_ACCESS_TOKEN, "header");
// }
// /**
// * JWT token
// * @return
// */
// private List<Parameter> setHeaderToken() {
// ParameterBuilder tokenPar = new ParameterBuilder();
// List<Parameter> pars = new ArrayList<>();
// tokenPar.name(CommonConstant.X_ACCESS_TOKEN).description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
// pars.add(tokenPar.build());
// return pars;
// }
//
// /**
// * api文档的详细信息函数,注意这里的注解引用的是哪个
// *
// * @return
// */
// private ApiInfo apiInfo() {
// return new ApiInfoBuilder()
// // //大标题
// .title("JeecgBoot 后台服务API接口文档")
// // 版本号
// .version("1.0")
//// .termsOfServiceUrl("NO terms of service")
// // 描述
// .description("后台API接口")
// // 作者
// .contact(new Contact("北京国炬信息技术有限公司","www.jeccg.com","jeecgos@163.com"))
// .license("The Apache License, Version 2.0")
// .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
// .build();
// }
//
// /**
// * 新增 securityContexts 保持登录状态
// */
// private List<SecurityContext> securityContexts() {
// return new ArrayList(
// Collections.singleton(SecurityContext.builder()
// .securityReferences(defaultAuth())
// .forPaths(PathSelectors.regex("^(?!auth).*$"))
// .build())
// );
// }
//
// private List<SecurityReference> defaultAuth() {
// AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
// AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
// authorizationScopes[0] = authorizationScope;
// return new ArrayList(
// Collections.singleton(new SecurityReference(CommonConstant.X_ACCESS_TOKEN, authorizationScopes)));
// }
//
// /**
// * 解决springboot2.6 和springfox不兼容问题
// * @return
// */
// @Bean
// public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
// return new BeanPostProcessor() {
//
// @Override
// public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
// customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
// }
// return bean;
// }
//
// private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
// List<T> copy = mappings.stream()
// .filter(mapping -> mapping.getPatternParser() == null)
// .collect(Collectors.toList());
// mappings.clear();
// mappings.addAll(copy);
// }
//
// @SuppressWarnings("unchecked")
// private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
// try {
// Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
// field.setAccessible(true);
// return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
// } catch (IllegalArgumentException | IllegalAccessException e) {
// throw new IllegalStateException(e);
// }
// }
// };
// }
//
//
//}
package org.jeecg.config;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.constant.CommonConstant;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* @Author scott
*/
@Configuration
@EnableSwagger2WebMvc
@Import(BeanValidatorPluginsConfiguration.class)
public class Swagger2Config implements WebMvcConfigurer {
/**
*
* 显示swagger-ui.html文档展示页还必须注入swagger资源
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
/**
* swagger2的配置文件这里可以配置swagger2的一些基本的内容比如扫描的包等等
*
* @return Docket
*/
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//此包路径下的类,才生成接口文档
.apis(RequestHandlerSelectors.basePackage("org.jeecg"))
//加了ApiOperation注解的类才生成接口文档
.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
.securitySchemes(Collections.singletonList(securityScheme()))
.securityContexts(securityContexts())
.globalOperationParameters(setHeaderToken());
}
/***
* oauth2配置
* 需要增加swagger授权回调地址
* http://localhost:8888/webjars/springfox-swagger-ui/o2c.html
* @return
*/
@Bean
SecurityScheme securityScheme() {
return new ApiKey(CommonConstant.X_ACCESS_TOKEN, CommonConstant.X_ACCESS_TOKEN, "header");
}
/**
* JWT token
* @return
*/
private List<Parameter> setHeaderToken() {
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
tokenPar.name(CommonConstant.X_ACCESS_TOKEN).description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return pars;
}
/**
* api文档的详细信息函数,注意这里的注解引用的是哪个
*
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// //大标题
.title("JeecgBoot 后台服务API接口文档")
// 版本号
.version("1.0")
// .termsOfServiceUrl("NO terms of service")
// 描述
.description("后台API接口")
// 作者
.contact(new Contact("北京国炬信息技术有限公司","www.jeccg.com","jeecgos@163.com"))
.license("The Apache License, Version 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.build();
}
/**
* 新增 securityContexts 保持登录状态
*/
private List<SecurityContext> securityContexts() {
return new ArrayList(
Collections.singleton(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build())
);
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return new ArrayList(
Collections.singleton(new SecurityReference(CommonConstant.X_ACCESS_TOKEN, authorizationScopes)));
}
/**
* 解决springboot2.6 和springfox不兼容问题
* @return
*/
@Bean
public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider) {
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
}
return bean;
}
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
List<T> copy = mappings.stream()
.filter(mapping -> mapping.getPatternParser() == null)
.collect(Collectors.toList());
mappings.clear();
mappings.addAll(copy);
}
@SuppressWarnings("unchecked")
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
try {
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
field.setAccessible(true);
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
};
}
}

View File

@ -1,59 +0,0 @@
package org.jeecg.config;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Paths;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.jeecg.common.constant.CommonConstant;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class Swagger3Config implements WebMvcConfigurer {
/**
*
* 显示swagger-ui.html文档展示页还必须注入swagger资源
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Bean
public GroupedOpenApi swaggerOpenApi() {
return GroupedOpenApi.builder()
.group("default")
.packagesToScan("org.jeecg")
// 剔除以下几个包路径的接口生成文档
.packagesToExclude("org.jeecg.modules.drag", "org.jeecg.modules.online", "org.jeecg.modules.jmreport")
// 加了Operation注解的方法才生成接口文档
.addOpenApiMethodFilter(method -> method.isAnnotationPresent(Operation.class))
.build();
}
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("JeecgBoot 后台服务API接口文档")
.version("1.0")
.contact(new Contact().name("北京国炬信息技术有限公司").url("www.jeccg.com").email("jeecgos@163.com"))
.description( "后台API接口")
.termsOfService("NO terms of service")
.license(new License().name("Apache 2.0").url("http://www.apache.org/licenses/LICENSE-2.0.html"))
);
}
}

View File

@ -1,19 +0,0 @@
package org.jeecg.config;
import io.undertow.server.DefaultByteBufferPool;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;
@Component
public class UndertowCustomizer implements WebServerFactoryCustomizer<UndertowServletWebServerFactory> {
@Override
public void customize(UndertowServletWebServerFactory factory) {
factory.addDeploymentInfoCustomizers(deploymentInfo -> {
WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(false, 1024));
deploymentInfo.addServletContextAttribute("io.undertow.websockets.jsr.WebSocketDeploymentInfo", webSocketDeploymentInfo);
});
}
}

View File

@ -10,20 +10,20 @@ import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.actuate.web.exchanges.InMemoryHttpExchangeRepository;
import org.springframework.boot.actuate.trace.http.InMemoryHttpTraceRepository;
import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@ -33,12 +33,14 @@ import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
/**
* Spring Boot 2.0 解决跨域问题
@ -57,6 +59,11 @@ public class WebMvcConfiguration implements WebMvcConfigurer {
@Autowired(required = false)
private PrometheusMeterRegistry prometheusMeterRegistry;
@Autowired
private ObjectProvider<Jackson2ObjectMapperBuilder> builderProvider;
@Autowired
private JacksonProperties jacksonProperties;
/**
* 静态资源的配置 - 使得可以从磁盘中读取 Html、图片、视频、音频等
*/
@ -109,6 +116,10 @@ public class WebMvcConfiguration implements WebMvcConfigurer {
@Primary
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
// 继承spring jackson 默认机制
if (Objects.nonNull(builderProvider.getIfAvailable())) {
objectMapper = builderProvider.getIfAvailable().createXmlMapper(false).build();
}
//处理bigDecimal
objectMapper.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN);
objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
@ -117,8 +128,10 @@ public class WebMvcConfiguration implements WebMvcConfigurer {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES, false);
//默认的处理日期时间格式
//默认的处理日期时间格式,接受通过spring.jackson.date-format配置格式化模式
if (Objects.isNull(jacksonProperties.getDateFormat())) {
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
@ -130,17 +143,16 @@ public class WebMvcConfiguration implements WebMvcConfigurer {
return objectMapper;
}
/**
* SpringBootAdmin的Httptrace不见了
* https://blog.csdn.net/u013810234/article/details/110097201
*/
@Bean
public InMemoryHttpExchangeRepository getInMemoryHttpTrace(){
InMemoryHttpExchangeRepository repository = new InMemoryHttpExchangeRepository();
// 默认保存1000条http请求记录
repository.setCapacity(1000);
return repository;
}
//update-begin---author:chenrui ---date:20240514 for[QQYUN-9247]系统监控功能优化------------
// /**
// * SpringBootAdmin的Httptrace不见了
// * https://blog.csdn.net/u013810234/article/details/110097201
// */
// @Bean
// public InMemoryHttpTraceRepository getInMemoryHttpTrace(){
// return new InMemoryHttpTraceRepository();
// }
//update-end---author:chenrui ---date:20240514 for[QQYUN-9247]系统监控功能优化------------
/**

View File

@ -31,7 +31,7 @@ public class WebSocketConfig {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(websocketFilter());
//TODO 临时注释掉测试下线上socket总断的问题
bean.addUrlPatterns("/websocket/*","/eoaSocket/*","/eoaNewChatSocket/*", "/newsWebsocket/*", "/vxeSocket/*");
bean.addUrlPatterns("/taskCountSocket/*", "/websocket/*","/eoaSocket/*","/eoaNewChatSocket/*", "/newsWebsocket/*", "/vxeSocket/*");
return bean;
}

View File

@ -3,8 +3,8 @@ package org.jeecg.config.filter;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.config.sign.util.BodyReaderHttpServletRequestWrapper;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**

View File

@ -7,9 +7,9 @@ import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**

View File

@ -2,21 +2,24 @@ package org.jeecg.config.firewall.interceptor;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.config.security.utils.SecureUtil;
import org.jeecg.config.firewall.interceptor.enums.LowCodeUrlsEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;
@ -63,12 +66,12 @@ public class LowCodeModeInterceptor implements HandlerInterceptor {
if (jeecgBaseConfig.getFirewall()!=null && LowCodeModeInterceptor.LOW_CODE_MODE_PROD.equals(jeecgBaseConfig.getFirewall().getLowCodeMode())) {
String requestURI = request.getRequestURI().substring(request.getContextPath().length());
log.info("低代码模式,拦截请求路径:" + requestURI);
LoginUser loginUser = SecureUtil.currentUser();
LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
Set<String> hasRoles = null;
if (loginUser == null) {
loginUser = commonAPI.getUserByName(JwtUtil.getUserNameByToken(SpringContextUtils.getHttpServletRequest()));
//当前登录人拥有的角色
hasRoles = commonAPI.queryUserRoles(loginUser.getUsername());
hasRoles = commonAPI.queryUserRolesById(loginUser.getId());
}
log.info("get loginUser info: {}", loginUser);

View File

@ -6,11 +6,13 @@ import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.TenantConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.security.utils.SecureUtil;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
@ -94,7 +96,24 @@ public class MybatisInterceptor implements Interceptor {
field.setAccessible(false);
if (localTenantId == null) {
field.setAccessible(true);
field.set(parameter, oConvertUtils.getInt(TenantContext.getTenant(),0));
String tenantId = TenantContext.getTenant();
//如果通过线程获取租户ID为空则通过当前请求的request获取租户shiro排除拦截器的请求会获取不到租户ID
if(oConvertUtils.isEmpty(tenantId) && MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL){
try {
tenantId = TokenUtils.getTenantIdByRequest(SpringContextUtils.getHttpServletRequest());
} catch (Exception e) {
//e.printStackTrace();
}
}
if (field.getType().equals(String.class)) {
// 字段类型为String
field.set(parameter, tenantId);
} else {
// 字段类型不是String
field.set(parameter, oConvertUtils.getInt(tenantId, 0));
}
field.setAccessible(false);
}
}
@ -173,7 +192,7 @@ public class MybatisInterceptor implements Interceptor {
private LoginUser getLoginUser() {
LoginUser sysUser = null;
try {
sysUser = SecureUtil.currentUser() != null ? SecureUtil.currentUser() : null;
sysUser = SecurityUtils.getSubject().getPrincipal() != null ? (LoginUser) SecurityUtils.getSubject().getPrincipal() : null;
} catch (Exception e) {
//e.printStackTrace();
sysUser = null;

View File

@ -30,7 +30,7 @@ import net.sf.jsqlparser.expression.LongValue;
*
*/
@Configuration
@MapperScan(value={"org.jeecg.modules.**.mapper*"})
@MapperScan(value={"org.jeecg.**.mapper*"})
public class MybatisPlusSaasConfig {
/**

View File

@ -11,7 +11,7 @@ import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.config.mybatis.ThreadLocalDataHelper;
import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
/**

View File

@ -6,8 +6,8 @@ import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 动态数据源切换拦截器

View File

@ -1,90 +0,0 @@
package org.jeecg.config.security;
import lombok.AllArgsConstructor;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat;
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.Set;
/**
* spring authorization server 注册客户端便捷工具类
* @author eightmonth@qq.com
* @date 2024/3/7 11:22
*/
@Component
@AllArgsConstructor
public class ClientService {
private RegisteredClientRepository registeredClientRepository;
/**
* 修改客户端token有效期
* 认证码、设备码有效期与accessToken有效期保持一致
*/
public void updateTokenValidation(String clientId, Long accessTokenValidation, Long refreshTokenValidation){
RegisteredClient registeredClient = findByClientId(clientId);
RegisteredClient.Builder builder = RegisteredClient.from(registeredClient);
TokenSettings tokenSettings = TokenSettings.builder()
.idTokenSignatureAlgorithm(SignatureAlgorithm.RS256)
.accessTokenTimeToLive(Duration.ofSeconds(accessTokenValidation))
.accessTokenFormat(OAuth2TokenFormat.SELF_CONTAINED)
.reuseRefreshTokens(true)
.refreshTokenTimeToLive(Duration.ofSeconds(refreshTokenValidation))
.authorizationCodeTimeToLive(Duration.ofSeconds(accessTokenValidation))
.deviceCodeTimeToLive(Duration.ofSeconds(accessTokenValidation))
.build();
builder.tokenSettings(tokenSettings);
registeredClientRepository.save(builder.build());
}
/**
* 修改客户端授权类型
* @param clientId
* @param grantTypes
*/
public void updateGrantType(String clientId, Set<AuthorizationGrantType> grantTypes) {
RegisteredClient registeredClient = findByClientId(clientId);
RegisteredClient.Builder builder = RegisteredClient.from(registeredClient);
for (AuthorizationGrantType grantType : grantTypes) {
builder.authorizationGrantType(grantType);
}
registeredClientRepository.save(builder.build());
}
/**
* 修改客户端重定向uri
* @param clientId
* @param redirectUris
*/
public void updateRedirectUris(String clientId, String redirectUris) {
RegisteredClient registeredClient = findByClientId(clientId);
RegisteredClient.Builder builder = RegisteredClient.from(registeredClient);
builder.redirectUri(redirectUris);
registeredClientRepository.save(builder.build());
}
/**
* 修改客户端授权范围
* @param clientId
* @param scopes
*/
public void updateScopes(String clientId, Set<String> scopes) {
RegisteredClient registeredClient = findByClientId(clientId);
RegisteredClient.Builder builder = RegisteredClient.from(registeredClient);
for (String scope : scopes) {
builder.scope(scope);
}
registeredClientRepository.save(builder.build());
}
public RegisteredClient findByClientId(String clientId) {
return registeredClientRepository.findByClientId(clientId);
}
}

View File

@ -1,100 +0,0 @@
package org.jeecg.config.security;
import cn.hutool.core.util.ArrayUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.config.security.utils.SecureUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
/**
* spring authorization server自定义权限处理根据@PreAuthorize注解判断当前用户是否具备权限
* @author EightMonth
* @date 2024/1/10 17:00
*/
@Service("jps")
@AllArgsConstructor
@Slf4j
public class JeecgPermissionService {
private final String SPLIT = "::";
private final String PERM_PREFIX = "jps" + SPLIT;
private final CommonAPI commonAPI;
private final RedisUtil redisUtil;
/**
* 判断接口是否有任意xxxxxx权限
* @param permissions 权限
* @return {boolean}
*/
public boolean requiresPermissions(String... permissions) {
if (ArrayUtil.isEmpty(permissions)) {
return false;
}
LoginUser loginUser = SecureUtil.currentUser();
Object cache = redisUtil.get(buildKey("permission", loginUser.getUsername()));
Set<String> permissionList;
if (Objects.nonNull(cache)) {
permissionList = (Set<String>) cache;
} else {
permissionList = commonAPI.queryUserAuths(loginUser.getUsername());
redisUtil.set(buildKey("permission", loginUser.getUsername()), permissionList);
}
boolean pass = permissionList.stream().filter(StringUtils::hasText)
.anyMatch(x -> PatternMatchUtils.simpleMatch(permissions, x));
if (!pass) {
log.error("权限不足,缺少权限:"+ Arrays.toString(permissions));
}
return pass;
}
/**
* 判断接口是否有任意xxxxxx角色
* @param roles 角色
* @return {boolean}
*/
public boolean requiresRoles(String... roles) {
if (ArrayUtil.isEmpty(roles)) {
return false;
}
LoginUser loginUser = SecureUtil.currentUser();
Object cache = redisUtil.get(buildKey("role", loginUser.getUsername()));
Set<String> roleList;
if (Objects.nonNull(cache)) {
roleList = (Set<String>) cache;
} else {
roleList = commonAPI.queryUserRoles(loginUser.getUsername());
redisUtil.set(buildKey("role", loginUser.getUsername()), roleList);
}
boolean pass = roleList.stream().filter(StringUtils::hasText)
.anyMatch(x -> PatternMatchUtils.simpleMatch(roles, x));
if (!pass) {
log.error("权限不足,缺少角色:" + Arrays.toString(roles));
}
return pass;
}
/**
* 由于缓存key是以人的维度角色列表、权限列表在值中jeecg是以权限列表绑定在角色上形成的权限集合
* 权限发生变更时,需要清理全部人的权限缓存
*/
public void clearCache() {
redisUtil.removeAll(PERM_PREFIX);
}
private String buildKey(String type, String username) {
return PERM_PREFIX + type + SPLIT + username;
}
}

View File

@ -1,54 +0,0 @@
package org.jeecg.config.security;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsent;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.util.concurrent.TimeUnit;
/**
* spring authorization server 自定义redis保存授权范围信息
*/
@Component
@RequiredArgsConstructor
public class JeecgRedisOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService {
private final RedisTemplate<String, Object> redisTemplate;
private final static Long TIMEOUT = 10L;
@Override
public void save(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
redisTemplate.opsForValue().set(buildKey(authorizationConsent), authorizationConsent, TIMEOUT,
TimeUnit.MINUTES);
}
@Override
public void remove(OAuth2AuthorizationConsent authorizationConsent) {
Assert.notNull(authorizationConsent, "authorizationConsent cannot be null");
redisTemplate.delete(buildKey(authorizationConsent));
}
@Override
public OAuth2AuthorizationConsent findById(String registeredClientId, String principalName) {
Assert.hasText(registeredClientId, "registeredClientId cannot be empty");
Assert.hasText(principalName, "principalName cannot be empty");
return (OAuth2AuthorizationConsent) redisTemplate.opsForValue()
.get(buildKey(registeredClientId, principalName));
}
private static String buildKey(String registeredClientId, String principalName) {
return "token:consent:" + registeredClientId + ":" + principalName;
}
private static String buildKey(OAuth2AuthorizationConsent authorizationConsent) {
return buildKey(authorizationConsent.getRegisteredClientId(), authorizationConsent.getPrincipalName());
}
}

View File

@ -1,181 +0,0 @@
package org.jeecg.config.security;
import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationCode;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* spring authorization server自定义redis保存认证信息
* @author EightMonth
*/
@Component
@RequiredArgsConstructor
public class JeecgRedisOAuth2AuthorizationService implements OAuth2AuthorizationService {
private final static Long TIMEOUT = 10L;
private static final String AUTHORIZATION = "token";
private final RedisTemplate<String, Object> redisTemplate;
@Override
public void save(OAuth2Authorization authorization) {
Assert.notNull(authorization, "authorization cannot be null");
if (isState(authorization)) {
String token = authorization.getAttribute("state");
redisTemplate.setValueSerializer(RedisSerializer.java());
redisTemplate.opsForValue().set(buildKey(OAuth2ParameterNames.STATE, token), authorization, TIMEOUT,
TimeUnit.MINUTES);
}
if (isCode(authorization)) {
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
.getToken(OAuth2AuthorizationCode.class);
OAuth2AuthorizationCode authorizationCodeToken = authorizationCode.getToken();
long between = ChronoUnit.MINUTES.between(authorizationCodeToken.getIssuedAt(),
authorizationCodeToken.getExpiresAt());
redisTemplate.setValueSerializer(RedisSerializer.java());
redisTemplate.opsForValue().set(buildKey(OAuth2ParameterNames.CODE, authorizationCodeToken.getTokenValue()),
authorization, between, TimeUnit.MINUTES);
}
if (isRefreshToken(authorization)) {
OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken();
long between = ChronoUnit.SECONDS.between(refreshToken.getIssuedAt(), refreshToken.getExpiresAt());
redisTemplate.setValueSerializer(RedisSerializer.java());
redisTemplate.opsForValue().set(buildKey(OAuth2ParameterNames.REFRESH_TOKEN, refreshToken.getTokenValue()),
authorization, between, TimeUnit.SECONDS);
}
if (isAccessToken(authorization)) {
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
long between = ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt());
redisTemplate.setValueSerializer(RedisSerializer.java());
redisTemplate.opsForValue().set(buildKey(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue()),
authorization, between, TimeUnit.SECONDS);
// 扩展记录 access-token 、username 的关系 1::token::username::admin::xxx
String tokenUsername = String.format("%s::%s::%s", AUTHORIZATION, authorization.getPrincipalName(), accessToken.getTokenValue());
redisTemplate.opsForValue().set(tokenUsername, accessToken.getTokenValue(), between, TimeUnit.SECONDS);
}
}
@Override
public void remove(OAuth2Authorization authorization) {
Assert.notNull(authorization, "authorization cannot be null");
List<String> keys = new ArrayList<>();
if (isState(authorization)) {
String token = authorization.getAttribute("state");
keys.add(buildKey(OAuth2ParameterNames.STATE, token));
}
if (isCode(authorization)) {
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
.getToken(OAuth2AuthorizationCode.class);
OAuth2AuthorizationCode authorizationCodeToken = authorizationCode.getToken();
keys.add(buildKey(OAuth2ParameterNames.CODE, authorizationCodeToken.getTokenValue()));
}
if (isRefreshToken(authorization)) {
OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken();
keys.add(buildKey(OAuth2ParameterNames.REFRESH_TOKEN, refreshToken.getTokenValue()));
}
if (isAccessToken(authorization)) {
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
keys.add(buildKey(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue()));
// 扩展记录 access-token 、username 的关系 1::token::username::admin::xxx
String key = String.format("%s::%s::%s", AUTHORIZATION, authorization.getPrincipalName(), accessToken.getTokenValue());
keys.add(key);
}
redisTemplate.delete(keys);
}
@Override
@Nullable
public OAuth2Authorization findById(String id) {
throw new UnsupportedOperationException();
}
@Override
@Nullable
public OAuth2Authorization findByToken(String token, @Nullable OAuth2TokenType tokenType) {
Assert.hasText(token, "token cannot be empty");
Assert.notNull(tokenType, "tokenType cannot be empty");
redisTemplate.setValueSerializer(RedisSerializer.java());
return (OAuth2Authorization) redisTemplate.opsForValue().get(buildKey(tokenType.getValue(), token));
}
private String buildKey(String type, String id) {
return String.format("%s::%s::%s", AUTHORIZATION, type, id);
}
private static boolean isState(OAuth2Authorization authorization) {
return Objects.nonNull(authorization.getAttribute("state"));
}
private static boolean isCode(OAuth2Authorization authorization) {
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
.getToken(OAuth2AuthorizationCode.class);
return Objects.nonNull(authorizationCode);
}
private static boolean isRefreshToken(OAuth2Authorization authorization) {
return Objects.nonNull(authorization.getRefreshToken());
}
private static boolean isAccessToken(OAuth2Authorization authorization) {
return Objects.nonNull(authorization.getAccessToken());
}
/**
* 扩展方法根据 username 查询是否存在存储的
* @param authentication
* @return
*/
public void removeByUsername(Authentication authentication) {
// 根据 username查询对应access-token
String authenticationName = authentication.getName();
// 扩展记录 access-token 、username 的关系 1::token::username::admin::xxx
String tokenUsernameKey = String.format("%s::%s::*", AUTHORIZATION, authenticationName);
Set<String> keys = redisTemplate.keys(tokenUsernameKey);
if (CollUtil.isEmpty(keys)) {
return;
}
List<Object> tokenList = redisTemplate.opsForValue().multiGet(keys);
for (Object token : tokenList) {
// 根据token 查询存储的 OAuth2Authorization
OAuth2Authorization authorization = this.findByToken((String) token, OAuth2TokenType.ACCESS_TOKEN);
// 根据 OAuth2Authorization 删除相关令牌
this.remove(authorization);
}
}
}

View File

@ -1,38 +0,0 @@
package org.jeecg.config.security;
/**
* 登录模式
* @author EightMonth
* @date 2024/1/10 17:43
*/
public class LoginType {
/**
* 密码模式
*/
public static final String PASSWORD = "password";
/**
* 手机号+验证码模式
*/
public static final String PHONE = "phone";
/**
* app登录
*/
public static final String APP = "app";
/**
* 扫码登录
*/
public static final String SCAN = "scan";
/**
* 所有联合登录比如github\钉钉\企业微信\微信
*/
public static final String SOCIAL = "social";
public static final String SELF = "self";
}

View File

@ -1,49 +0,0 @@
package org.jeecg.config.security;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.jeecg.common.system.util.JwtUtil;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.resource.BearerTokenErrors;
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.Objects;
/**
* 当用户被强退时使客户端token失效
* @author eightmonth@qq.com
* @date 2024/3/7 17:30
*/
@Component
@AllArgsConstructor
public class RedisTokenValidationFilter extends OncePerRequestFilter {
private OAuth2AuthorizationService authorizationService;
private JwtDecoder jwtDecoder;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// 从请求中获取token
DefaultBearerTokenResolver defaultBearerTokenResolver = new DefaultBearerTokenResolver();
String token = defaultBearerTokenResolver.resolve(request);
if (Objects.nonNull(token)) {
// 检查认证信息是否已被清除如果已被清除则令该token失效
OAuth2Authorization oAuth2Authorization = authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
if (Objects.isNull(oAuth2Authorization)) {
throw new OAuth2AuthenticationException(BearerTokenErrors.invalidToken("认证信息已失效,请重新登录"));
}
}
filterChain.doFilter(request, response);
}
}

View File

@ -1,262 +0,0 @@
package org.jeecg.config.security;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import lombok.AllArgsConstructor;
import org.jeecg.config.security.app.AppGrantAuthenticationConvert;
import org.jeecg.config.security.app.AppGrantAuthenticationProvider;
import org.jeecg.config.security.password.PasswordGrantAuthenticationConvert;
import org.jeecg.config.security.password.PasswordGrantAuthenticationProvider;
import org.jeecg.config.security.phone.PhoneGrantAuthenticationConvert;
import org.jeecg.config.security.phone.PhoneGrantAuthenticationProvider;
import org.jeecg.config.security.social.SocialGrantAuthenticationConvert;
import org.jeecg.config.security.social.SocialGrantAuthenticationProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
import org.springframework.security.oauth2.server.authorization.token.*;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.header.writers.frameoptions.RegExpAllowFromStrategy;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Arrays;
import java.util.List;
/**
* spring authorization server核心配置
* @author eightmonth@qq.com
* @date 2024/1/2 9:29
*/
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@AllArgsConstructor
public class SecurityConfig {
private JdbcTemplate jdbcTemplate;
private OAuth2AuthorizationService authorizationService;
@Bean
@Order(1)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http)
throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
// 注册自定义登录类型
http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
.tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new PasswordGrantAuthenticationConvert())
.authenticationProvider(new PasswordGrantAuthenticationProvider(authorizationService, tokenGenerator())))
.tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new PhoneGrantAuthenticationConvert())
.authenticationProvider(new PhoneGrantAuthenticationProvider(authorizationService, tokenGenerator())))
.tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new AppGrantAuthenticationConvert())
.authenticationProvider(new AppGrantAuthenticationProvider(authorizationService, tokenGenerator())))
.tokenEndpoint(tokenEndpoint -> tokenEndpoint.accessTokenRequestConverter(new SocialGrantAuthenticationConvert())
.authenticationProvider(new SocialGrantAuthenticationProvider(authorizationService, tokenGenerator())))
//开启OpenID Connect 1.0其中oidc为OpenID Connect的缩写。 访问 /.well-known/openid-configuration即可获取认证信息
.oidc(Customizer.withDefaults());
http
//将需要认证的请求重定向到login页面行登录认证。
.exceptionHandling((exceptions) -> exceptions
.defaultAuthenticationEntryPointFor(
new LoginUrlAuthenticationEntryPoint("/sys/login"),
new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
)
)
// 使用jwt处理接收到的access token
.oauth2ResourceServer(oauth2ResourceServer ->
oauth2ResourceServer.jwt(Customizer.withDefaults()));
return http.build();
}
@Bean
@Order(2)
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
throws Exception {
http
//设置所有请求都需要认证未认证的请求都被重定向到login页面进行登录
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/cas/client/validateLogin")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/randomImage/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/checkCaptcha")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/login")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/mLogin")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/logout")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/thirdLogin/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/getEncryptedString")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/sms")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/phoneLogin")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/user/checkOnlyUser")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/user/register")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/user/phoneVerification")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/user/passwordChange")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/auth/2step-code")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/common/static/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/common/pdf/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/generic/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/getLoginQrcode/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/getQrcodeToken/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/checkAuth")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/doc.html")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.js")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.css")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.html")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.svg")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.pdf")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.jpg")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.png")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.gif")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.ico")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.ttf")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.woff")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.woff2")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/druid/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/swagger-ui.html")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/swagger**/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/webjars/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/v3/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/WW_verify*")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/sys/annountCement/show/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/jmreport/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.js.map")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/**/*.css.map")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/view")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/page/queryById")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/onlDragDatasetHead/getAllChartData")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/onlDragDatasetHead/getTotalData")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/mock/json/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/test/bigScreen/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/bigscreen/template1/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/bigscreen/template1/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/websocket/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/newsWebsocket/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/vxeSocket/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/test/seata/**")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/error")).permitAll()
.anyRequest().authenticated()
)
.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
.cors(cors -> cors
.configurationSource(req -> {
CorsConfiguration config = new CorsConfiguration();
config.applyPermitDefaultValues();
config.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
return config;
}))
.csrf(AbstractHttpConfigurer::disable)
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}
/**
* 数据库保存注册客户端信息
*/
@Bean
public RegisteredClientRepository registeredClientRepository() {
return new JdbcRegisteredClientRepository(jdbcTemplate);
}
/**
*配置 JWK为JWT(id_token)提供加密密钥,用于加密/解密或签名/验签
* JWK详细见https://datatracker.ietf.org/doc/html/draft-ietf-jose-json-web-key-41
*/
@Bean
public JWKSource<SecurityContext> jwkSource() {
KeyPair keyPair = generateRsaKey();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAKey rsaKey = new RSAKey.Builder(publicKey)
.privateKey(privateKey)
// 重要!生产环境需要修改!
.keyID("jeecg")
.build();
JWKSet jwkSet = new JWKSet(rsaKey);
return new ImmutableJWKSet<>(jwkSet);
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
/**
*生成RSA密钥对给上面jwkSource() 方法的提供密钥对
*/
private static KeyPair generateRsaKey() {
KeyPair keyPair;
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
// 生产环境不应该设置secureRandomseed如果被泄露jwt容易被伪造
// 如果不设置secureRandom会存在一个问题当应用重启后原有的token将会全部失效因为重启的keyPair与之前已经不同
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
// 重要!生产环境需要修改!
secureRandom.setSeed("jeecg".getBytes());
keyPairGenerator.initialize(2048, secureRandom);
keyPair = keyPairGenerator.generateKeyPair();
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
return keyPair;
}
/**
* 配置jwt解析器
*/
@Bean
public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
}
/**
*配置认证服务器请求地址
*/
@Bean
public AuthorizationServerSettings authorizationServerSettings() {
return AuthorizationServerSettings.builder().tokenEndpoint("/sys/login").build();
}
/**
*配置token生成器
*/
@Bean
OAuth2TokenGenerator<?> tokenGenerator() {
JwtGenerator jwtGenerator = new JwtGenerator(new NimbusJwtEncoder(jwkSource()));
OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
return new DelegatingOAuth2TokenGenerator(
jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
}
}

View File

@ -1,81 +0,0 @@
package org.jeecg.config.security.app;
import jakarta.servlet.http.HttpServletRequest;
import org.jeecg.config.security.LoginType;
import org.jeecg.config.security.password.PasswordGrantAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* APP模式认证转换器
* @author EightMonth
* @date 2024/1/1
*/
public class AppGrantAuthenticationConvert implements AuthenticationConverter {
@Override
public Authentication convert(HttpServletRequest request) {
String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
if (!LoginType.APP.equals(grantType)) {
return null;
}
Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication();
//从request中提取请求参数然后存入MultiValueMap<String, String>
MultiValueMap<String, String> parameters = getParameters(request);
// username (REQUIRED)
String username = parameters.getFirst(OAuth2ParameterNames.USERNAME);
if (!StringUtils.hasText(username) ||
parameters.get(OAuth2ParameterNames.USERNAME).size() != 1) {
throw new OAuth2AuthenticationException("无效请求,用户名不能为空!");
}
String password = parameters.getFirst(OAuth2ParameterNames.PASSWORD);
if (!StringUtils.hasText(password) ||
parameters.get(OAuth2ParameterNames.PASSWORD).size() != 1) {
throw new OAuth2AuthenticationException("无效请求,密码不能为空!");
}
//收集要传入PasswordGrantAuthenticationToken构造方法的参数
//该参数接下来在PasswordGrantAuthenticationProvider中使用
Map<String, Object> additionalParameters = new HashMap<>();
//遍历从request中提取的参数排除掉grant_type、client_id、code等字段参数其他参数收集到additionalParameters中
parameters.forEach((key, value) -> {
if (!key.equals(OAuth2ParameterNames.GRANT_TYPE) &&
!key.equals(OAuth2ParameterNames.CLIENT_ID) &&
!key.equals(OAuth2ParameterNames.CODE)) {
additionalParameters.put(key, value.get(0));
}
});
//返回自定义的PasswordGrantAuthenticationToken对象
return new PasswordGrantAuthenticationToken(clientPrincipal, additionalParameters);
}
/**
*从request中提取请求参数然后存入MultiValueMap<String, String>
*/
private static MultiValueMap<String, String> getParameters(HttpServletRequest request) {
Map<String, String[]> parameterMap = request.getParameterMap();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(parameterMap.size());
parameterMap.forEach((key, values) -> {
if (values.length > 0) {
for (String value : values) {
parameters.add(key, value);
}
}
});
return parameters;
}
}

View File

@ -1,318 +0,0 @@
package org.jeecg.config.security.app;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.exception.JeecgCaptchaException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysDepartModel;
import org.jeecg.common.util.Md5Util;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.config.security.password.PasswordGrantAuthenticationToken;
import org.jeecg.modules.base.service.BaseCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.*;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.context.AuthorizationServerContextHolder;
import org.springframework.security.oauth2.server.authorization.token.DefaultOAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.security.Principal;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* APP模式认证处理器负责处理该认证模式下的核心逻辑
* @author EightMonth
* @date 2024/1/1
*/
@Slf4j
public class AppGrantAuthenticationProvider implements AuthenticationProvider {
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
private final OAuth2AuthorizationService authorizationService;
private final OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator;
@Autowired
private CommonAPI commonAPI;
@Autowired
private RedisUtil redisUtil;
@Autowired
private JeecgBaseConfig jeecgBaseConfig;
@Autowired
private BaseCommonService baseCommonService;
public AppGrantAuthenticationProvider(OAuth2AuthorizationService authorizationService, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator) {
Assert.notNull(authorizationService, "authorizationService cannot be null");
Assert.notNull(tokenGenerator, "tokenGenerator cannot be null");
this.authorizationService = authorizationService;
this.tokenGenerator = tokenGenerator;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
AppGrantAuthenticationToken appGrantAuthenticationToken = (AppGrantAuthenticationToken) authentication;
Map<String, Object> additionalParameter = appGrantAuthenticationToken.getAdditionalParameters();
// 授权类型
AuthorizationGrantType authorizationGrantType = appGrantAuthenticationToken.getGrantType();
// 用户名
String username = (String) additionalParameter.get(OAuth2ParameterNames.USERNAME);
// 密码
String password = (String) additionalParameter.get(OAuth2ParameterNames.PASSWORD);
//请求参数权限范围
String requestScopesStr = (String)additionalParameter.getOrDefault(OAuth2ParameterNames.SCOPE, "*");
//请求参数权限范围专场集合
Set<String> requestScopeSet = Stream.of(requestScopesStr.split(" ")).collect(Collectors.toSet());
// 验证码
String captcha = (String) additionalParameter.get("captcha");
String checkKey = (String) additionalParameter.get("checkKey");
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(appGrantAuthenticationToken);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
// 检查登录失败次数
if(isLoginFailOvertimes(username)){
Map<String, Object> map = new HashMap<>();
map.put("message", "该用户登录失败次数过多请于10分钟后再次登录");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
if(captcha==null){
Map<String, Object> map = new HashMap<>();
map.put("message", "验证码无效");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
String lowerCaseCaptcha = captcha.toLowerCase();
// 加入密钥作为混淆,避免简单的拼接,被外部利用,用户自定义该密钥即可
String origin = lowerCaseCaptcha+checkKey+jeecgBaseConfig.getSignatureSecret();
String realKey = Md5Util.md5Encode(origin, "utf-8");
Object checkCode = redisUtil.get(realKey);
//当进入登录页时,有一定几率出现验证码错误 #1714
if(checkCode==null || !checkCode.toString().equals(lowerCaseCaptcha)) {
Map<String, Object> map = new HashMap<>();
map.put("message", "验证码错误");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
if (!registeredClient.getAuthorizationGrantTypes().contains(authorizationGrantType)) {
Map<String, Object> map = new HashMap<>();
map.put("message", "非法登录");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
// 通过用户名获取用户信息
LoginUser loginUser = commonAPI.getUserByName(username);
//update-begin---author:eightmonth ---date:2024-04-30 for【6168】master分支切sas分支登录发生错误-----------
if (Objects.isNull(loginUser) || !StringUtils.hasText(loginUser.getSalt())) {
redisUtil.del(CacheConstant.SYS_USERS_CACHE+"::"+username);
loginUser = commonAPI.getUserByName(username);
}
//update-end---author:eightmonth ---date::2024-04-30 for【6168】master分支切sas分支登录发生错误--------------
// 检查用户可行性
checkUserIsEffective(loginUser);
// 不使用spring security passwordEncoder针对密码进行匹配使用自有加密匹配针对 spring security使用noop传输
password = PasswordUtil.encrypt(username, password, loginUser.getSalt());
if (!password.equals(loginUser.getPassword())) {
addLoginFailOvertimes(username);
Map<String, Object> map = new HashMap<>();
map.put("message", "用户名或密码不正确");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
//由于在上面已验证过用户名、密码现在构建一个已认证的对象UsernamePasswordAuthenticationToken
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = UsernamePasswordAuthenticationToken.authenticated(loginUser,clientPrincipal,new ArrayList<>());
DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder()
.registeredClient(registeredClient)
.principal(usernamePasswordAuthenticationToken)
.authorizationServerContext(AuthorizationServerContextHolder.getContext())
.authorizationGrantType(authorizationGrantType)
.authorizedScopes(requestScopeSet)
.authorizationGrant(appGrantAuthenticationToken);
OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.withRegisteredClient(registeredClient)
.principalName(clientPrincipal.getName())
.authorizedScopes(requestScopeSet)
.attribute(Principal.class.getName(), username)
.authorizationGrantType(authorizationGrantType);
// ----- Access token -----
OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build();
OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext);
if (generatedAccessToken == null) {
Map<String, Object> map = new HashMap<>();
map.put("message", "无法生成访问token请联系管理系。");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(),
generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
if (generatedAccessToken instanceof ClaimAccessor) {
authorizationBuilder.token(accessToken, (metadata) -> {
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims());
});
} else {
authorizationBuilder.accessToken(accessToken);
}
// ----- Refresh token -----
OAuth2RefreshToken refreshToken = null;
if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) &&
// 不向公共客户端颁发刷新令牌
!clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) {
tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) {
Map<String, Object> map = new HashMap<>();
map.put("message", "无法生成刷新token请联系管理员。");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
refreshToken = (OAuth2RefreshToken) generatedRefreshToken;
authorizationBuilder.refreshToken(refreshToken);
}
OAuth2Authorization authorization = authorizationBuilder.build();
// 保存认证信息至redis
authorizationService.save(authorization);
// 登录成功删除redis中的验证码
redisUtil.del(realKey);
redisUtil.del(CommonConstant.LOGIN_FAIL + username);
baseCommonService.addLog("用户名: " + username + ",登录成功!", CommonConstant.LOG_TYPE_1, null,loginUser);
JSONObject addition = new JSONObject(new LinkedHashMap<>());
addition.put("token", accessToken.getTokenValue());
// 设置租户
JSONObject jsonObject = commonAPI.setLoginTenant(username);
addition.putAll(jsonObject.getInnerMap());
// 设置登录用户信息
addition.put("userInfo", loginUser);
addition.put("sysAllDictItems", commonAPI.queryAllDictItems());
List<SysDepartModel> departs = commonAPI.queryUserDeparts(loginUser.getId());
addition.put("departs", departs);
if (departs == null || departs.size() == 0) {
addition.put("multi_depart", 0);
} else if (departs.size() == 1) {
commonAPI.updateUserDepart(username, departs.get(0).getOrgCode(),null);
addition.put("multi_depart", 1);
} else {
//查询当前是否有登录部门
if(oConvertUtils.isEmpty(loginUser.getOrgCode())){
commonAPI.updateUserDepart(username, departs.get(0).getOrgCode(),null);
}
addition.put("multi_depart", 2);
}
// 兼容原有shiro登录结果处理
Map<String, Object> map = new HashMap<>();
map.put("result", addition);
map.put("code", 200);
map.put("success", true);
map.put("timestamp", System.currentTimeMillis());
// 返回access_token、refresh_token以及其它信息给到前端
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken, refreshToken, map);
}
@Override
public boolean supports(Class<?> authentication) {
return AppGrantAuthenticationToken.class.isAssignableFrom(authentication);
}
private static OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient(Authentication authentication) {
OAuth2ClientAuthenticationToken clientPrincipal = null;
if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication.getPrincipal().getClass())) {
clientPrincipal = (OAuth2ClientAuthenticationToken) authentication.getPrincipal();
}
if (clientPrincipal != null && clientPrincipal.isAuthenticated()) {
return clientPrincipal;
}
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
}
/**
* 登录失败超出次数5 返回true
* @param username
* @return
*/
private boolean isLoginFailOvertimes(String username){
String key = CommonConstant.LOGIN_FAIL + username;
Object failTime = redisUtil.get(key);
if(failTime!=null){
Integer val = Integer.parseInt(failTime.toString());
if(val>5){
return true;
}
}
return false;
}
/**
* 记录登录失败次数
* @param username
*/
private void addLoginFailOvertimes(String username){
String key = CommonConstant.LOGIN_FAIL + username;
Object failTime = redisUtil.get(key);
Integer val = 0;
if(failTime!=null){
val = Integer.parseInt(failTime.toString());
}
// 10分钟
redisUtil.set(key, ++val, 10);
}
/**
* 校验用户是否有效
*/
private void checkUserIsEffective(LoginUser loginUser) {
//情况1根据用户信息查询该用户不存在
if (Objects.isNull(loginUser)) {
baseCommonService.addLog("用户登录失败,用户不存在!", CommonConstant.LOG_TYPE_1, null);
throw new JeecgBootException("该用户不存在,请注册");
}
//情况2根据用户信息查询该用户已注销
//update-begin---author:王帅 Date:20200601 forif条件永远为falsebug------------
if (CommonConstant.DEL_FLAG_1.equals(loginUser.getDelFlag())) {
//update-end---author:王帅 Date:20200601 forif条件永远为falsebug------------
baseCommonService.addLog("用户登录失败,用户名:" + loginUser.getUsername() + "已注销!", CommonConstant.LOG_TYPE_1, null);
throw new JeecgBootException("该用户已注销");
}
//情况3根据用户信息查询该用户已冻结
if (CommonConstant.USER_FREEZE.equals(loginUser.getStatus())) {
baseCommonService.addLog("用户登录失败,用户名:" + loginUser.getUsername() + "已冻结!", CommonConstant.LOG_TYPE_1, null);
throw new JeecgBootException("该用户已冻结");
}
}
}

View File

@ -1,21 +0,0 @@
package org.jeecg.config.security.app;
import org.jeecg.config.security.LoginType;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationGrantAuthenticationToken;
import java.util.Map;
/**
* APP模式认证专用token类型方法spring authorization server进行认证流转配合convert使用
* @author EightMonth
* @date 2024/1/1
*/
public class AppGrantAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
public AppGrantAuthenticationToken(Authentication clientPrincipal, Map<String, Object> additionalParameters) {
super(new AuthorizationGrantType(LoginType.APP), clientPrincipal, additionalParameters);
}
}

View File

@ -1,82 +0,0 @@
package org.jeecg.config.security.password;
import jakarta.servlet.http.HttpServletRequest;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.config.security.LoginType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* 密码模式认证转换器
* @author EightMonth
* @date 2024/1/1
*/
public class PasswordGrantAuthenticationConvert implements AuthenticationConverter {
@Override
public Authentication convert(HttpServletRequest request) {
String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
if (!LoginType.PASSWORD.equals(grantType)) {
return null;
}
Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication();
//从request中提取请求参数然后存入MultiValueMap<String, String>
MultiValueMap<String, String> parameters = getParameters(request);
// username (REQUIRED)
String username = parameters.getFirst(OAuth2ParameterNames.USERNAME);
if (!StringUtils.hasText(username) ||
parameters.get(OAuth2ParameterNames.USERNAME).size() != 1) {
throw new OAuth2AuthenticationException("无效请求,用户名不能为空!");
}
String password = parameters.getFirst(OAuth2ParameterNames.PASSWORD);
if (!StringUtils.hasText(password) ||
parameters.get(OAuth2ParameterNames.PASSWORD).size() != 1) {
throw new OAuth2AuthenticationException("无效请求,密码不能为空!");
}
//收集要传入PasswordGrantAuthenticationToken构造方法的参数
//该参数接下来在PasswordGrantAuthenticationProvider中使用
Map<String, Object> additionalParameters = new HashMap<>();
//遍历从request中提取的参数排除掉grant_type、client_id、code等字段参数其他参数收集到additionalParameters中
parameters.forEach((key, value) -> {
if (!key.equals(OAuth2ParameterNames.GRANT_TYPE) &&
!key.equals(OAuth2ParameterNames.CLIENT_ID) &&
!key.equals(OAuth2ParameterNames.CODE)) {
additionalParameters.put(key, value.get(0));
}
});
//返回自定义的PasswordGrantAuthenticationToken对象
return new PasswordGrantAuthenticationToken(clientPrincipal, additionalParameters);
}
/**
*从request中提取请求参数然后存入MultiValueMap<String, String>
*/
private static MultiValueMap<String, String> getParameters(HttpServletRequest request) {
Map<String, String[]> parameterMap = request.getParameterMap();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(parameterMap.size());
parameterMap.forEach((key, values) -> {
if (values.length > 0) {
for (String value : values) {
parameters.add(key, value);
}
}
});
return parameters;
}
}

View File

@ -1,317 +0,0 @@
package org.jeecg.config.security.password;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.exception.JeecgCaptchaException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysDepartModel;
import org.jeecg.common.util.Md5Util;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.modules.base.service.BaseCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.core.*;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.context.AuthorizationServerContextHolder;
import org.springframework.security.oauth2.server.authorization.token.DefaultOAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.security.Principal;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 密码模式认证处理器,负责处理该认证模式下的核心逻辑
* @author EightMonth
* @date 2024/1/1
*/
@Slf4j
public class PasswordGrantAuthenticationProvider implements AuthenticationProvider {
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
private final OAuth2AuthorizationService authorizationService;
private final OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator;
@Autowired
private CommonAPI commonAPI;
@Autowired
private RedisUtil redisUtil;
@Autowired
private JeecgBaseConfig jeecgBaseConfig;
@Autowired
private BaseCommonService baseCommonService;
public PasswordGrantAuthenticationProvider(OAuth2AuthorizationService authorizationService, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator) {
Assert.notNull(authorizationService, "authorizationService cannot be null");
Assert.notNull(tokenGenerator, "tokenGenerator cannot be null");
this.authorizationService = authorizationService;
this.tokenGenerator = tokenGenerator;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
PasswordGrantAuthenticationToken passwordGrantAuthenticationToken = (PasswordGrantAuthenticationToken) authentication;
Map<String, Object> additionalParameter = passwordGrantAuthenticationToken.getAdditionalParameters();
// 授权类型
AuthorizationGrantType authorizationGrantType = passwordGrantAuthenticationToken.getGrantType();
// 用户名
String username = (String) additionalParameter.get(OAuth2ParameterNames.USERNAME);
// 密码
String password = (String) additionalParameter.get(OAuth2ParameterNames.PASSWORD);
//请求参数权限范围
String requestScopesStr = (String)additionalParameter.getOrDefault(OAuth2ParameterNames.SCOPE, "*");
//请求参数权限范围专场集合
Set<String> requestScopeSet = Stream.of(requestScopesStr.split(" ")).collect(Collectors.toSet());
// 验证码
String captcha = (String) additionalParameter.get("captcha");
String checkKey = (String) additionalParameter.get("checkKey");
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(passwordGrantAuthenticationToken);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
// 检查登录失败次数
if(isLoginFailOvertimes(username)){
throw new JeecgBootException("该用户登录失败次数过多请于10分钟后再次登录");
}
if(captcha==null){
throw new JeecgBootException("验证码无效");
}
String lowerCaseCaptcha = captcha.toLowerCase();
// 加入密钥作为混淆,避免简单的拼接,被外部利用,用户自定义该密钥即可
String origin = lowerCaseCaptcha+checkKey+jeecgBaseConfig.getSignatureSecret();
String realKey = Md5Util.md5Encode(origin, "utf-8");
Object checkCode = redisUtil.get(realKey);
//当进入登录页时,有一定几率出现验证码错误 #1714
if(checkCode==null || !checkCode.toString().equals(lowerCaseCaptcha)) {
Map<String, Object> map = new HashMap<>();
map.put("message", "验证码错误");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
if (!registeredClient.getAuthorizationGrantTypes().contains(authorizationGrantType)) {
Map<String, Object> map = new HashMap<>();
map.put("message", "非法登录");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
// 通过用户名获取用户信息
LoginUser loginUser = commonAPI.getUserByName(username);
//update-begin---author:eightmonth ---date:2024-04-30 for【6168】master分支切sas分支登录发生错误-----------
if (Objects.isNull(loginUser) || !StringUtils.hasText(loginUser.getSalt())) {
redisUtil.del(CacheConstant.SYS_USERS_CACHE+"::"+username);
loginUser = commonAPI.getUserByName(username);
}
//update-end---author:eightmonth ---date::2024-04-30 for【6168】master分支切sas分支登录发生错误--------------
// 检查用户可行性
checkUserIsEffective(loginUser);
// 不使用spring security passwordEncoder针对密码进行匹配使用自有加密匹配针对 spring security使用noop传输
password = PasswordUtil.encrypt(username, password, loginUser.getSalt());
if (!password.equals(loginUser.getPassword())) {
addLoginFailOvertimes(username);
Map<String, Object> map = new HashMap<>();
map.put("message", "用户名或密码不正确");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
//由于在上面已验证过用户名、密码现在构建一个已认证的对象UsernamePasswordAuthenticationToken
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = UsernamePasswordAuthenticationToken.authenticated(loginUser,clientPrincipal,new ArrayList<>());
DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder()
.registeredClient(registeredClient)
.principal(usernamePasswordAuthenticationToken)
.authorizationServerContext(AuthorizationServerContextHolder.getContext())
.authorizationGrantType(authorizationGrantType)
.authorizedScopes(requestScopeSet)
.authorizationGrant(passwordGrantAuthenticationToken);
OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.withRegisteredClient(registeredClient)
.principalName(clientPrincipal.getName())
.authorizedScopes(requestScopeSet)
.attribute(Principal.class.getName(), username)
.authorizationGrantType(authorizationGrantType);
// ----- Access token -----
OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build();
OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext);
if (generatedAccessToken == null) {
Map<String, Object> map = new HashMap<>();
map.put("message", "无法生成访问token请联系管理系。");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(),
generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
if (generatedAccessToken instanceof ClaimAccessor) {
authorizationBuilder.token(accessToken, (metadata) -> {
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims());
});
} else {
authorizationBuilder.accessToken(accessToken);
}
// ----- Refresh token -----
OAuth2RefreshToken refreshToken = null;
if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) &&
// 不向公共客户端颁发刷新令牌
!clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) {
tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) {
Map<String, Object> map = new HashMap<>();
map.put("message", "无法生成访问token请联系管理系。");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
refreshToken = (OAuth2RefreshToken) generatedRefreshToken;
authorizationBuilder.refreshToken(refreshToken);
}
OAuth2Authorization authorization = authorizationBuilder.build();
// 保存认证信息至redis
authorizationService.save(authorization);
// 登录成功删除redis中的验证码
redisUtil.del(realKey);
redisUtil.del(CommonConstant.LOGIN_FAIL + username);
baseCommonService.addLog("用户名: " + username + ",登录成功!", CommonConstant.LOG_TYPE_1, null,loginUser);
JSONObject addition = new JSONObject(new LinkedHashMap<>());
addition.put("token", accessToken.getTokenValue());
// 设置租户
JSONObject jsonObject = commonAPI.setLoginTenant(username);
addition.putAll(jsonObject.getInnerMap());
// 设置登录用户信息
addition.put("userInfo", loginUser);
addition.put("sysAllDictItems", commonAPI.queryAllDictItems());
List<SysDepartModel> departs = commonAPI.queryUserDeparts(loginUser.getId());
addition.put("departs", departs);
if (departs == null || departs.size() == 0) {
addition.put("multi_depart", 0);
} else if (departs.size() == 1) {
commonAPI.updateUserDepart(username, departs.get(0).getOrgCode(),null);
addition.put("multi_depart", 1);
} else {
//查询当前是否有登录部门
if(oConvertUtils.isEmpty(loginUser.getOrgCode())){
commonAPI.updateUserDepart(username, departs.get(0).getOrgCode(),null);
}
addition.put("multi_depart", 2);
}
// 兼容原有shiro登录结果处理
Map<String, Object> map = new HashMap<>();
map.put("result", addition);
map.put("code", 200);
map.put("success", true);
map.put("timestamp", System.currentTimeMillis());
// 返回access_token、refresh_token以及其它信息给到前端
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken, refreshToken, map);
}
@Override
public boolean supports(Class<?> authentication) {
return PasswordGrantAuthenticationToken.class.isAssignableFrom(authentication);
}
private static OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient(Authentication authentication) {
OAuth2ClientAuthenticationToken clientPrincipal = null;
if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication.getPrincipal().getClass())) {
clientPrincipal = (OAuth2ClientAuthenticationToken) authentication.getPrincipal();
}
if (clientPrincipal != null && clientPrincipal.isAuthenticated()) {
return clientPrincipal;
}
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
}
/**
* 登录失败超出次数5 返回true
* @param username
* @return
*/
private boolean isLoginFailOvertimes(String username){
String key = CommonConstant.LOGIN_FAIL + username;
Object failTime = redisUtil.get(key);
if(failTime!=null){
Integer val = Integer.parseInt(failTime.toString());
if(val>5){
return true;
}
}
return false;
}
/**
* 记录登录失败次数
* @param username
*/
private void addLoginFailOvertimes(String username){
String key = CommonConstant.LOGIN_FAIL + username;
Object failTime = redisUtil.get(key);
Integer val = 0;
if(failTime!=null){
val = Integer.parseInt(failTime.toString());
}
// 10分钟
redisUtil.set(key, ++val, 10);
}
/**
* 校验用户是否有效
*/
private void checkUserIsEffective(LoginUser loginUser) {
//情况1根据用户信息查询该用户不存在
if (Objects.isNull(loginUser)) {
baseCommonService.addLog("用户登录失败,用户不存在!", CommonConstant.LOG_TYPE_1, null);
throw new JeecgBootException("该用户不存在,请注册");
}
//情况2根据用户信息查询该用户已注销
//update-begin---author:王帅 Date:20200601 forif条件永远为falsebug------------
if (CommonConstant.DEL_FLAG_1.equals(loginUser.getDelFlag())) {
//update-end---author:王帅 Date:20200601 forif条件永远为falsebug------------
baseCommonService.addLog("用户登录失败,用户名:" + loginUser.getUsername() + "已注销!", CommonConstant.LOG_TYPE_1, null);
throw new JeecgBootException("该用户已注销");
}
//情况3根据用户信息查询该用户已冻结
if (CommonConstant.USER_FREEZE.equals(loginUser.getStatus())) {
baseCommonService.addLog("用户登录失败,用户名:" + loginUser.getUsername() + "已冻结!", CommonConstant.LOG_TYPE_1, null);
throw new JeecgBootException("该用户已冻结");
}
}
}

View File

@ -1,21 +0,0 @@
package org.jeecg.config.security.password;
import org.jeecg.config.security.LoginType;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationGrantAuthenticationToken;
import java.util.Map;
/**
* 密码模式认证专用token类型方法spring authorization server进行认证流转配合convert使用
* @author EightMonth
* @date 2024/1/1
*/
public class PasswordGrantAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
public PasswordGrantAuthenticationToken(Authentication clientPrincipal, Map<String, Object> additionalParameters) {
super(new AuthorizationGrantType(LoginType.PASSWORD), clientPrincipal, additionalParameters);
}
}

View File

@ -1,77 +0,0 @@
package org.jeecg.config.security.phone;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.jeecg.config.security.LoginType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* 手机号模式认证转换器
* @author EightMonth
* @date 2024/1/1
*/
@AllArgsConstructor
public class PhoneGrantAuthenticationConvert implements AuthenticationConverter {
@Override
public Authentication convert(HttpServletRequest request) {
String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
if (!LoginType.PHONE.equals(grantType)) {
return null;
}
Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication();
//从request中提取请求参数然后存入MultiValueMap<String, String>
MultiValueMap<String, String> parameters = getParameters(request);
// 验证码
String captcha = parameters.getFirst("captcha");
if (!StringUtils.hasText(captcha)) {
throw new OAuth2AuthenticationException("无效请求,验证码不能为空!");
}
//收集要传入PhoneGrantAuthenticationToken构造方法的参数
//该参数接下来在PhoneGrantAuthenticationProvider中使用
Map<String, Object> additionalParameters = new HashMap<>();
//遍历从request中提取的参数排除掉grant_type、client_id、code等字段参数其他参数收集到additionalParameters中
parameters.forEach((key, value) -> {
if (!key.equals(OAuth2ParameterNames.GRANT_TYPE) &&
!key.equals(OAuth2ParameterNames.CLIENT_ID) &&
!key.equals(OAuth2ParameterNames.CODE)) {
additionalParameters.put(key, value.get(0));
}
});
//返回自定义的PhoneGrantAuthenticationToken对象
return new PhoneGrantAuthenticationToken(clientPrincipal, additionalParameters);
}
/**
*从request中提取请求参数然后存入MultiValueMap<String, String>
*/
private static MultiValueMap<String, String> getParameters(HttpServletRequest request) {
Map<String, String[]> parameterMap = request.getParameterMap();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(parameterMap.size());
parameterMap.forEach((key, values) -> {
if (values.length > 0) {
for (String value : values) {
parameters.add(key, value);
}
}
});
return parameters;
}
}

View File

@ -1,290 +0,0 @@
package org.jeecg.config.security.phone;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.exception.JeecgCaptchaException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysDepartModel;
import org.jeecg.common.util.Md5Util;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.config.security.password.PasswordGrantAuthenticationToken;
import org.jeecg.modules.base.service.BaseCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.*;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.context.AuthorizationServerContextHolder;
import org.springframework.security.oauth2.server.authorization.token.DefaultOAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.util.Assert;
import java.security.Principal;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 手机号模式认证处理器,负责处理该认证模式下的核心逻辑
* @author EightMonth
* @date 2024/1/1
*/
@Slf4j
public class PhoneGrantAuthenticationProvider implements AuthenticationProvider {
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
private final OAuth2AuthorizationService authorizationService;
private final OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator;
@Autowired
private CommonAPI commonAPI;
@Autowired
private RedisUtil redisUtil;
@Autowired
private JeecgBaseConfig jeecgBaseConfig;
@Autowired
private BaseCommonService baseCommonService;
public PhoneGrantAuthenticationProvider(OAuth2AuthorizationService authorizationService, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator) {
Assert.notNull(authorizationService, "authorizationService cannot be null");
Assert.notNull(tokenGenerator, "tokenGenerator cannot be null");
this.authorizationService = authorizationService;
this.tokenGenerator = tokenGenerator;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
PhoneGrantAuthenticationToken phoneGrantAuthenticationToken = (PhoneGrantAuthenticationToken) authentication;
Map<String, Object> additionalParameter = phoneGrantAuthenticationToken.getAdditionalParameters();
// 授权类型
AuthorizationGrantType authorizationGrantType = phoneGrantAuthenticationToken.getGrantType();
// 手机号
String phone = (String) additionalParameter.get("mobile");
if(isLoginFailOvertimes(phone)){
throw new JeecgBootException("该用户登录失败次数过多请于10分钟后再次登录");
}
//请求参数权限范围
String requestScopesStr = (String)additionalParameter.getOrDefault(OAuth2ParameterNames.SCOPE, "*");
//请求参数权限范围专场集合
Set<String> requestScopeSet = Stream.of(requestScopesStr.split(" ")).collect(Collectors.toSet());
// 验证码
String captcha = (String) additionalParameter.get("captcha");
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(phoneGrantAuthenticationToken);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
// 通过手机号获取用户信息
LoginUser loginUser = commonAPI.getUserByPhone(phone);
// 检查用户可行性
checkUserIsEffective(loginUser);
String redisKey = CommonConstant.PHONE_REDIS_KEY_PRE+phone;
Object code = redisUtil.get(redisKey);
if (!captcha.equals(code)) {
//update-begin-author:taoyan date:2022-11-7 for: issues/4109 平台用户登录失败锁定用户
addLoginFailOvertimes(phone);
Map<String, Object> map = new HashMap<>();
map.put("message", "手机验证码错误");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
if (!registeredClient.getAuthorizationGrantTypes().contains(authorizationGrantType)) {
Map<String, Object> map = new HashMap<>();
map.put("message", "非法登录");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
//由于在上面已验证过用户名、密码现在构建一个已认证的对象UsernamePasswordAuthenticationToken
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = UsernamePasswordAuthenticationToken.authenticated(loginUser,clientPrincipal,new ArrayList<>());
DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder()
.registeredClient(registeredClient)
.principal(usernamePasswordAuthenticationToken)
.authorizationServerContext(AuthorizationServerContextHolder.getContext())
.authorizationGrantType(authorizationGrantType)
.authorizedScopes(requestScopeSet)
.authorizationGrant(phoneGrantAuthenticationToken);
OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.withRegisteredClient(registeredClient)
.principalName(clientPrincipal.getName())
.authorizedScopes(requestScopeSet)
.attribute(Principal.class.getName(), loginUser.getUsername())
.authorizationGrantType(authorizationGrantType);
// ----- Access token -----
OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build();
OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext);
if (generatedAccessToken == null) {
Map<String, Object> map = new HashMap<>();
map.put("message", "无法生成刷新token请联系管理员。");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(),
generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
if (generatedAccessToken instanceof ClaimAccessor) {
authorizationBuilder.token(accessToken, (metadata) -> {
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims());
});
} else {
authorizationBuilder.accessToken(accessToken);
}
// ----- Refresh token -----
OAuth2RefreshToken refreshToken = null;
if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) &&
// 不向公共客户端颁发刷新令牌
!clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) {
tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) {
Map<String, Object> map = new HashMap<>();
map.put("message", "无法生成刷新token请联系管理员。");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
refreshToken = (OAuth2RefreshToken) generatedRefreshToken;
authorizationBuilder.refreshToken(refreshToken);
}
OAuth2Authorization authorization = authorizationBuilder.build();
// 保存认证信息至redis
authorizationService.save(authorization);
baseCommonService.addLog("用户名: " + loginUser.getUsername() + ",登录成功!", CommonConstant.LOG_TYPE_1, null,loginUser);
JSONObject addition = new JSONObject(new LinkedHashMap<>());
addition.put("token", accessToken.getTokenValue());
// 设置租户
JSONObject jsonObject = commonAPI.setLoginTenant(loginUser.getUsername());
addition.putAll(jsonObject.getInnerMap());
// 设置登录用户信息
addition.put("userInfo", loginUser);
addition.put("sysAllDictItems", commonAPI.queryAllDictItems());
List<SysDepartModel> departs = commonAPI.queryUserDeparts(loginUser.getId());
addition.put("departs", departs);
if (departs == null || departs.size() == 0) {
addition.put("multi_depart", 0);
} else if (departs.size() == 1) {
commonAPI.updateUserDepart(loginUser.getUsername(), departs.get(0).getOrgCode(),null);
addition.put("multi_depart", 1);
} else {
//查询当前是否有登录部门
if(oConvertUtils.isEmpty(loginUser.getOrgCode())){
commonAPI.updateUserDepart(loginUser.getUsername(), departs.get(0).getOrgCode(),null);
}
addition.put("multi_depart", 2);
}
// 兼容原有shiro登录结果处理
Map<String, Object> map = new HashMap<>();
map.put("result", addition);
map.put("code", 200);
map.put("success", true);
map.put("timestamp", System.currentTimeMillis());
// 返回access_token、refresh_token以及其它信息给到前端
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken, refreshToken, map);
}
@Override
public boolean supports(Class<?> authentication) {
return PhoneGrantAuthenticationToken.class.isAssignableFrom(authentication);
}
private static OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient(Authentication authentication) {
OAuth2ClientAuthenticationToken clientPrincipal = null;
if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication.getPrincipal().getClass())) {
clientPrincipal = (OAuth2ClientAuthenticationToken) authentication.getPrincipal();
}
if (clientPrincipal != null && clientPrincipal.isAuthenticated()) {
return clientPrincipal;
}
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
}
/**
* 登录失败超出次数5 返回true
* @param username
* @return
*/
private boolean isLoginFailOvertimes(String username){
String key = CommonConstant.LOGIN_FAIL + username;
Object failTime = redisUtil.get(key);
if(failTime!=null){
Integer val = Integer.parseInt(failTime.toString());
if(val>5){
return true;
}
}
return false;
}
/**
* 记录登录失败次数
* @param username
*/
private void addLoginFailOvertimes(String username){
String key = CommonConstant.LOGIN_FAIL + username;
Object failTime = redisUtil.get(key);
Integer val = 0;
if(failTime!=null){
val = Integer.parseInt(failTime.toString());
}
// 10分钟
redisUtil.set(key, ++val, 10);
}
/**
* 校验用户是否有效
*/
private void checkUserIsEffective(LoginUser loginUser) {
//情况1根据用户信息查询该用户不存在
if (Objects.isNull(loginUser)) {
baseCommonService.addLog("用户登录失败,用户不存在!", CommonConstant.LOG_TYPE_1, null);
throw new JeecgBootException("该用户不存在,请注册");
}
//情况2根据用户信息查询该用户已注销
//update-begin---author:王帅 Date:20200601 forif条件永远为falsebug------------
if (CommonConstant.DEL_FLAG_1.equals(loginUser.getDelFlag())) {
//update-end---author:王帅 Date:20200601 forif条件永远为falsebug------------
baseCommonService.addLog("用户登录失败,用户名:" + loginUser.getUsername() + "已注销!", CommonConstant.LOG_TYPE_1, null);
throw new JeecgBootException("该用户已注销");
}
//情况3根据用户信息查询该用户已冻结
if (CommonConstant.USER_FREEZE.equals(loginUser.getStatus())) {
baseCommonService.addLog("用户登录失败,用户名:" + loginUser.getUsername() + "已冻结!", CommonConstant.LOG_TYPE_1, null);
throw new JeecgBootException("该用户已冻结");
}
}
}

View File

@ -1,21 +0,0 @@
package org.jeecg.config.security.phone;
import org.jeecg.config.security.LoginType;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationGrantAuthenticationToken;
import java.util.Map;
/**
* 手机号模式认证专用token类型方法spring authorization server进行认证流转配合convert使用
* @author EightMonth
* @date 2024/1/1
*/
public class PhoneGrantAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
public PhoneGrantAuthenticationToken(Authentication clientPrincipal, Map<String, Object> additionalParameters) {
super(new AuthorizationGrantType(LoginType.PHONE), clientPrincipal, additionalParameters);
}
}

View File

@ -1,228 +0,0 @@
package org.jeecg.config.security.self;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysDepartModel;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.modules.base.service.BaseCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.*;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.token.DefaultOAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.security.Principal;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 自用生成token处理器不对外开放外部请求无法通过该方式生成token
* @author eightmonth@qq.com
* @date 2024/3/19 11:40
*/
@Component
public class SelfAuthenticationProvider implements AuthenticationProvider {
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
private final OAuth2AuthorizationService authorizationService;
private final OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator;
@Autowired
private CommonAPI commonAPI;
@Autowired
private RedisUtil redisUtil;
@Autowired
private JeecgBaseConfig jeecgBaseConfig;
@Autowired
private BaseCommonService baseCommonService;
public SelfAuthenticationProvider(OAuth2AuthorizationService authorizationService, OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator) {
Assert.notNull(authorizationService, "authorizationService cannot be null");
Assert.notNull(tokenGenerator, "tokenGenerator cannot be null");
this.authorizationService = authorizationService;
this.tokenGenerator = tokenGenerator;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
SelfAuthenticationToken passwordGrantAuthenticationToken = (SelfAuthenticationToken) authentication;
Map<String, Object> additionalParameter = passwordGrantAuthenticationToken.getAdditionalParameters();
// 授权类型
AuthorizationGrantType authorizationGrantType = passwordGrantAuthenticationToken.getGrantType();
// 用户名
String username = (String) additionalParameter.get(OAuth2ParameterNames.USERNAME);
//请求参数权限范围
String requestScopesStr = "*";
//请求参数权限范围专场集合
Set<String> requestScopeSet = Stream.of(requestScopesStr.split(" ")).collect(Collectors.toSet());
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(passwordGrantAuthenticationToken);
RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();
if (!registeredClient.getAuthorizationGrantTypes().contains(authorizationGrantType)) {
Map<String, Object> map = new HashMap<>();
map.put("message", "非法登录");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
// 通过用户名获取用户信息
LoginUser loginUser = commonAPI.getUserByName(username);
// 检查用户可行性
checkUserIsEffective(loginUser);
//由于在上面已验证过用户名、密码现在构建一个已认证的对象UsernamePasswordAuthenticationToken
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = UsernamePasswordAuthenticationToken.authenticated(loginUser,clientPrincipal,new ArrayList<>());
DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder()
.registeredClient(registeredClient)
.principal(usernamePasswordAuthenticationToken)
.authorizationGrantType(authorizationGrantType)
.authorizedScopes(requestScopeSet)
.authorizationGrant(passwordGrantAuthenticationToken);
OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.withRegisteredClient(registeredClient)
.principalName(clientPrincipal.getName())
.authorizedScopes(requestScopeSet)
.attribute(Principal.class.getName(), username)
.authorizationGrantType(authorizationGrantType);
// ----- Access token -----
OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build();
OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext);
if (generatedAccessToken == null) {
Map<String, Object> map = new HashMap<>();
map.put("message", "无法生成刷新token请联系管理员。");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(),
generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());
if (generatedAccessToken instanceof ClaimAccessor) {
authorizationBuilder.token(accessToken, (metadata) -> {
metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims());
});
} else {
authorizationBuilder.accessToken(accessToken);
}
// ----- Refresh token -----
OAuth2RefreshToken refreshToken = null;
if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) &&
// 不向公共客户端颁发刷新令牌
!clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) {
tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) {
Map<String, Object> map = new HashMap<>();
map.put("message", "无法生成刷新token请联系管理员。");
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,"fdsafas", Instant.now(), Instant.now().plusNanos(1)), null, map);
}
refreshToken = (OAuth2RefreshToken) generatedRefreshToken;
authorizationBuilder.refreshToken(refreshToken);
}
OAuth2Authorization authorization = authorizationBuilder.build();
// 保存认证信息至redis
authorizationService.save(authorization);
JSONObject addition = new JSONObject(new LinkedHashMap<>());
addition.put("token", accessToken.getTokenValue());
// 设置租户
JSONObject jsonObject = commonAPI.setLoginTenant(username);
addition.putAll(jsonObject.getInnerMap());
// 设置登录用户信息
addition.put("userInfo", loginUser);
addition.put("sysAllDictItems", commonAPI.queryAllDictItems());
List<SysDepartModel> departs = commonAPI.queryUserDeparts(loginUser.getId());
addition.put("departs", departs);
if (departs == null || departs.size() == 0) {
addition.put("multi_depart", 0);
} else if (departs.size() == 1) {
commonAPI.updateUserDepart(username, departs.get(0).getOrgCode(),null);
addition.put("multi_depart", 1);
} else {
//查询当前是否有登录部门
if(oConvertUtils.isEmpty(loginUser.getOrgCode())){
commonAPI.updateUserDepart(username, departs.get(0).getOrgCode(),null);
}
addition.put("multi_depart", 2);
}
// 兼容原有shiro登录结果处理
Map<String, Object> map = new HashMap<>();
map.put("result", addition);
map.put("code", 200);
map.put("success", true);
map.put("timestamp", System.currentTimeMillis());
// 返回access_token、refresh_token以及其它信息给到前端
return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken, refreshToken, map);
}
@Override
public boolean supports(Class<?> authentication) {
return SelfAuthenticationToken.class.isAssignableFrom(authentication);
}
private static OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient(Authentication authentication) {
OAuth2ClientAuthenticationToken clientPrincipal = null;
if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication.getPrincipal().getClass())) {
clientPrincipal = (OAuth2ClientAuthenticationToken) authentication.getPrincipal();
}
if (clientPrincipal != null && clientPrincipal.isAuthenticated()) {
return clientPrincipal;
}
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT);
}
/**
* 校验用户是否有效
*/
private void checkUserIsEffective(LoginUser loginUser) {
//情况1根据用户信息查询该用户不存在
if (Objects.isNull(loginUser)) {
baseCommonService.addLog("用户登录失败,用户不存在!", CommonConstant.LOG_TYPE_1, null);
throw new JeecgBootException("该用户不存在,请注册");
}
//情况2根据用户信息查询该用户已注销
//update-begin---author:王帅 Date:20200601 forif条件永远为falsebug------------
if (CommonConstant.DEL_FLAG_1.equals(loginUser.getDelFlag())) {
//update-end---author:王帅 Date:20200601 forif条件永远为falsebug------------
baseCommonService.addLog("用户登录失败,用户名:" + loginUser.getUsername() + "已注销!", CommonConstant.LOG_TYPE_1, null);
throw new JeecgBootException("该用户已注销");
}
//情况3根据用户信息查询该用户已冻结
if (CommonConstant.USER_FREEZE.equals(loginUser.getStatus())) {
baseCommonService.addLog("用户登录失败,用户名:" + loginUser.getUsername() + "已冻结!", CommonConstant.LOG_TYPE_1, null);
throw new JeecgBootException("该用户已冻结");
}
}
}

Some files were not shown because too many files have changed in this diff Show More