Compare commits

..

152 Commits

Author SHA1 Message Date
4d058e1dce 【issues/7561】主题切换为顶部混合模式时,页面顶部内容显示不出来,被遮盖 2024-12-17 09:43:18 +08:00
5c9c2dbebe 【issues/7548】侧边栏导航模式时会导致下面菜单滚动显示不全 2024-12-17 09:43:00 +08:00
44f7075316 账户设置->修改手机号:获取验证码接口 404 错误 #7587 2024-12-16 15:42:36 +08:00
c88bfcf35a v3.7.2发布,提供免费大屏 2024-12-12 19:48:26 +08:00
11d13c8305 v3.7.2 数据库脚本 2024-12-12 12:17:47 +08:00
0582436b9c v3.7.2 数据库脚本 2024-12-11 16:22:30 +08:00
ef16814216 v3.7.2 删除报错代码暂时无用 2024-12-10 15:42:10 +08:00
a626b6a4d0 快速体验入口 2024-12-09 20:02:38 +08:00
fca5d0e54e 新版发布 3.7.2 2024-12-09 17:56:20 +08:00
1c3b9a10f1 新版发布,升级3.7.2版本号 2024-12-09 17:07:38 +08:00
b0c4194602 v3.7.2 版本代码合并 2024-12-09 15:10:46 +08:00
64b29f47e0 其他数据库脚本,转库说明文档 2024-12-06 16:33:22 +08:00
6198a3702f 其他数据库脚本,转库说明文档 2024-12-06 16:32:33 +08:00
453acb9b4e 升级积木报表到最新版1.9.1,支持大屏 2024-12-04 09:58:40 +08:00
565753e370 运行时间好长,效率慢 #7491 2024-12-04 09:52:29 +08:00
e2aaf0f978 【issues/7500】vue-router4.5.0版本路由name:PageNotFound同名导致登录进不去 2024-11-27 18:41:24 +08:00
32c8370ef2 【issues/7500】vue-router4.5.0版本路由name:PageNotFound同名导致登录进不去 2024-11-27 10:51:44 +08:00
a79004b924 【issues/7488】手机号码登录,在请求头中无法获取租户id 2024-11-27 09:46:34 +08:00
eb1612f8dd 开源协议说明 2024-11-22 10:44:47 +08:00
a35555619c Merge pull request #7370 from EightMonth/master
使seata直接与springboot datasource挂钩
2024-11-20 10:30:39 +08:00
b3e3951064 【issues/7433】vue3 数据字典优化建议 2024-11-14 19:35:59 +08:00
44ec26574e 【issues/7402】CollapseContainer组件增加默认不展开属性 2024-11-12 09:37:49 +08:00
55a25caafd 【issues/7413】合计行有点对不齐 2024-11-12 09:36:53 +08:00
62f7b0d489 【issues/7442】basicTable从默认切换到宽松紧凑时多选框显示异常 2024-11-12 09:35:00 +08:00
b16fdef8dc 【issues/7422】BasicTable列表canResize属性为true时合计行不能横向滚动 2024-11-12 09:34:18 +08:00
b5b667058b 【issues/7405】部门选择用户同时全部选择两页用户,回显到父页面。第二页用户显示的不是真是姓名 2024-11-12 09:33:25 +08:00
6c0c259742 QQ群满,提交新群号 ⑩716488839 2024-10-29 11:45:00 +08:00
ca56c54aa0 升级seata server1.7.0版本sql 2024-10-24 10:52:23 +08:00
74297af987 使seata直接与springboot datasource挂钩 2024-10-22 14:09:02 +08:00
fedb6b84b9 Merge remote-tracking branch 'origin/master' 2024-10-21 11:30:20 +08:00
fdc713339e 引入AI能力,支持自动建表等功能; 2024-10-21 11:26:23 +08:00
f28a2dbbeb Merge pull request #7364 from 94464562/patch-1
remove dbsource from cache
2024-10-19 17:04:24 +08:00
b81435aaca remove dbsource from cache
remove dbsource from cache
2024-10-19 11:49:27 +08:00
48805484d4 MK编辑器,无法上传多个图片 2024-09-24 22:47:44 +08:00
7fecdf94e5 修改柱体颜色 2024-09-24 22:47:04 +08:00
a3997dfd16 【issues/7200】basicTable选中后没有选中样式 --- 2024-09-24 22:43:44 +08:00
c868d90c2f 【issues/7209】顶部左侧组合菜单关闭之后左侧导航没还原 --- 2024-09-24 22:43:06 +08:00
77aebf5dd2 租户套餐的菜单名称没国际化 2024-09-24 22:42:21 +08:00
e770524f3a 【issues/7203】自动生成一对多表单代码中,省市区回显问题-- 2024-09-24 22:41:34 +08:00
c5fee07cba 【issues/7136】单元格上的tooltip提示,如果表格有滚动条,会不跟着单元格滚动 2024-09-24 22:40:47 +08:00
9fd20fde9e 【issues/7250】自动锁屏无法解锁 2024-09-24 22:39:52 +08:00
2af9451b7f 【issues/7217】BasicTable树形表格设置checkStrictly无效 ---
【issues/7200】basicTable选中后没有选中样式 ---
2024-09-24 22:38:24 +08:00
575baa8d49 JeecgBoot3.7XSS漏洞处理 2024-09-14 14:15:31 +08:00
48bc76cce7 在线演示地址 2024-09-14 11:46:03 +08:00
58c0882329 更新README.md 2024-09-13 09:52:02 +08:00
c400ec8482 前端环境,要求Node 20+ 版本以上 2024-09-13 09:31:37 +08:00
2068bdc112 前端环境要求Node.js 版本建议v20.15.0 2024-09-13 09:29:01 +08:00
ffe806352e 前端环境要求Node.js 版本建议v20.15.0 2024-09-13 09:20:28 +08:00
167a6c458c 前端环境要求Node.js 版本建议v20.15.0 2024-09-13 09:18:36 +08:00
872e6ed024 开源协议中文释意 2024-09-13 09:10:45 +08:00
cc9384abb6 积木仪表盘升级到最新版1.8.1-beta 2024-09-11 22:22:02 +08:00
c346d0d6e6 flyway报错处理 2024-09-11 17:43:52 +08:00
2942d69fa1 Merge branch 'master' of https://github.com/zhangdaiscott/jeecg-boot 2024-09-11 10:32:02 +08:00
7d7cc3fb08 Merge pull request #7199 from EightMonth/master
修改redis docker 仓库源
2024-09-11 10:29:14 +08:00
0b84192c29 修改 2024-09-11 10:28:05 +08:00
9fde47957d 修改redis docker 仓库源 2024-09-11 10:27:49 +08:00
ae753f60fd 升级autopoi到最新版1.4.11 2024-09-11 09:31:49 +08:00
2d3b1418de 3.7.1版本发布 2024-09-10 19:48:03 +08:00
15f1ca953d 更新README.md 2024-09-10 16:25:38 +08:00
17180bfcd5 升级版本号3.7.1 2024-09-10 16:16:44 +08:00
c5ddea5c62 更新README.md 2024-09-10 15:51:49 +08:00
13cb18b707 3.7.1版本发布 2024-09-10 15:40:34 +08:00
17c68f6d53 3.7.1版本发布 2024-09-10 15:39:32 +08:00
39ca47d2ef tinymce优化 2024-09-09 09:32:27 +08:00
824f3c2b90 【TV360X-2314】 使用RestUitl类时发现RestTemplate超时 #7140 2024-09-04 23:02:32 +08:00
70607dbe2b 【issues/7101】列配置resizable: true时,表尾合计的列宽没有同步改变 2024-09-04 13:59:22 +08:00
7e2b4c68ec Merge remote-tracking branch 'origin/master' 2024-09-02 11:50:02 +08:00
5359fc4112 升级代码生成器依赖 2024-09-02 11:47:10 +08:00
c31a4e8ab4 Merge pull request #7142 from EightMonth/master
修复 #7081
2024-09-02 11:45:36 +08:00
2b773d6e6b 富文本编辑器,无法上传多个图片 #7076 2024-08-29 20:26:01 +08:00
996a56bd59 修复 #7081 2024-08-29 17:59:14 +08:00
4d48f9b500 Docker镜像源失效,把docker镜像源换成国内的 2024-08-26 17:18:06 +08:00
2570e454ed Docker镜像源失效,把docker镜像源换成国内的 2024-08-26 17:10:09 +08:00
4fd8ae1f94 Docker一键启动微服务前后端, mysql镜像找不到 #7119 2024-08-26 14:44:50 +08:00
72829aa2af 【issues/6999】ApiSelect联动更新字段不生效(代码还原) 2024-08-24 16:52:53 +08:00
0cada33e49 数据库配置默认增加达梦和人大金仓的配置,节省用户修改的成本 2024-08-22 19:30:55 +08:00
ca2a56248c Merge branch 'master' of https://github.com/zhangdaiscott/jeecg-boot 2024-08-22 15:15:04 +08:00
6846e9fdef Merge pull request #7058 from EightMonth/master
修复#6903,升级xxl-job 至2.4.1版本,规避CVE-2024-24113
2024-08-22 13:30:34 +08:00
33be0079f0 启动成功打印xxl-job-admin访问地址 2024-08-22 10:37:20 +08:00
31a865f5e0 修改xxl-job初始化sql 2024-08-22 09:51:44 +08:00
114f59f712 升级积木报表到1.8.0 2024-08-21 19:20:20 +08:00
7eef470d28 Merge pull request #6912 from xzs603/master
Update ShiroConfig.java
2024-08-21 10:07:33 +08:00
ae9e85d3f6 Merge pull request #7060 from youdianfan/patch-1
【issues/7044】生产环境关闭mock启用
2024-08-11 22:25:58 +08:00
In
e9ac37d118 【issues/7044】生产环境关闭mock启用 2024-08-09 23:03:18 +08:00
1d2b10c2a5 修复#6903,升级xxl-job 至2.4.1版本,规避CVE-2024-24113 2024-08-09 15:27:19 +08:00
34442b7226 JVxeTable表格Column配置formatter属性不生效 #6950] 2024-08-07 12:01:21 +08:00
c75e9bf05b 更新视频教程 2024-08-06 20:21:49 +08:00
d1ac35108d 类型修正 2024-08-05 13:55:01 +08:00
e0fb952146 【issues/6943】mock翻页之后数据id和图片没自动刷新 2024-08-05 13:53:48 +08:00
4aa4c57db4 【issues/6953】JTreeSelect 组件能支持antdv 对应的a-tree-select 组件的插槽
【issues/1283】JtreeSelect组件初始调用了两次接口
2024-08-05 13:52:54 +08:00
517600f9a4 【issues/6920】解决热更新ScrollContainer报错 --- 2024-08-05 13:50:53 +08:00
1c9e76931f 【issues/6957】editableCell组件值长度为0,无法编辑 2024-08-05 13:49:44 +08:00
d0f09480ca socket总断,换一个写法 2024-07-26 12:00:39 +08:00
e99deb1c33 更新仪表盘效果图 2024-07-26 11:00:05 +08:00
099e745b8f 还原jackson日期格式修改,导致online的带时间的日期值都带T 2024-07-24 20:03:22 +08:00
5898656227 mac系统谷歌浏览器企业微信第三方登录成功后没有弹出绑定手机弹窗 2024-07-19 11:42:18 +08:00
7dcf8f9b5a 【issues/6883】单选模式第二次打开已勾选 2024-07-19 11:41:06 +08:00
4753a74456 【issues/6855】组件使用key作props报警告,改为itemKey 2024-07-19 11:40:31 +08:00
0a76623c53 【issues/6865】配置单个的labelWidth不生效 2024-07-19 11:39:23 +08:00
cd6bb2ca04 Update ShiroConfig.java
当使用redis的sentinel模式时,如果设置了redis的密码但未设置sentinel密码,会造成失败。NOAUTH Authentication required.
2024-07-17 16:16:33 +08:00
819555e612 【代码生成器专项优化】
代码生成没有生成前端权限指令v-auth
代码生成支持新组件JPopupDict字典
查询条件范围控件更换美观的效果: 日期范围、数字范围、金额范围等
用户和部门组件,生成代码的时候需要根据Online存储字段和显示字段配置来
原生表单校验不通过,未滚到未通过校验的字段
非原生表单校验不通过,未滚到未通过校验的字段
详情页面触发了校验修复
ERP风格子表操作列没有浮动
页面控件类型为下拉框时,生成的前端vue代码冗余","
代码生成 int类型字段的查询条件,没有渲染成数值输入框
无论是原生erp还是非原生,不选中主表的时候,直接导出子表,发现导出了所有数据
一对多erp,也改成点击行就选中
一对Tab风格样式美化
2024-07-13 18:08:34 +08:00
0148a0b45e #6861 跳转到自定义首页死循环问题 2024-07-12 14:16:09 +08:00
7049e9974e 无用参数去掉 2024-07-11 10:49:08 +08:00
1243fe1cad 【issues/6681】异步查询不生效 2024-07-11 10:39:47 +08:00
b189e6de52 【issues/6851】editableCell组件值为0时不展示 2024-07-11 10:39:17 +08:00
5dd3bdc23f [issues/6368] rangeDate去掉判断允许起始项或结束项为空兼容allowEmpty 2024-07-11 10:38:07 +08:00
7015eef621 【issues/6374】暗黑主题按钮样式丢失 2024-07-11 10:37:18 +08:00
fd92d516ee nacos支持达梦数据库 2024-07-11 10:33:35 +08:00
606f079a93 解决jdk17 内存信息-立即更新 功能报错 #6635- 2024-07-10 16:00:11 +08:00
ab86013e7b 更新 2024-07-09 21:56:37 +08:00
11ac387559 达梦数据库的nacos初始化脚本 2024-07-09 18:02:34 +08:00
ec93d615f4 nacos默认mysql配置 2024-07-09 14:46:22 +08:00
fbebaf456b nacos升级兼容达梦数据库 2024-07-09 14:44:25 +08:00
7ea46609b1 升级jimureport到最新版1.7.8 2024-07-08 12:22:41 +08:00
e3cd6bfc97 升级jimureport到最新版1.7.7 2024-07-06 22:21:25 +08:00
8000d61ce0 修改项目语言 2024-07-05 15:53:18 +08:00
4ac18b5d81 项目语言修改 2024-07-05 15:49:11 +08:00
54676a4512 更新README.md 2024-07-02 09:27:34 +08:00
2d16d1c79c 更新README.md 2024-07-02 09:24:02 +08:00
3c7da54c3c 启动jar时报错:ElasticSearch 服务连接失败 2024-07-01 19:42:15 +08:00
434d1cca61 支持Docker一键启动微服务前后端 2024-06-29 18:34:01 +08:00
7b14b5df4a 简化docker启动微服务后台,删除jeecg-boot/jeecg-server-cloud/docker-compose-base.yml 2024-06-29 18:25:55 +08:00
befa0f0603 Merge pull request #6669 from EightMonth/master
新增微服务前后端一键启动
2024-06-29 16:18:53 +08:00
0ad9942e89 支持Docker一键启动前后端 2024-06-28 18:07:32 +08:00
41cfbd192c Merge branch 'master' of https://github.com/zhangdaiscott/jeecg-boot 2024-06-28 18:04:57 +08:00
0d79cccc52 支持Docker一键启动前后端 2024-06-28 18:01:08 +08:00
d51127a9b7 调整启动顺序 2024-06-28 17:36:57 +08:00
4a6110c618 新增j 2024-06-28 17:31:52 +08:00
b2bc848281 Merge pull request #6667 from EightMonth/master
新增jeecgboot一键前后端启动
2024-06-28 17:10:41 +08:00
65a12c1156 新增jeecgboot一键前后端启动 2024-06-28 15:40:43 +08:00
9070b4a1c7 提供分布式日志轻量级方案 Loki、grafana套件 2024-06-27 17:53:18 +08:00
6b56be941c 修复了MQ的问题
Shutdown Signal: channel error; protocol method: #method<channel.close>(reply-code=406, reply-text=PRECONDITION_FAILED - unknown delivery tag 1, class-id=60, method-id=80)
2024-06-27 15:34:42 +08:00
8064ea6abb nacos镜像下载失败替换为阿里云的 2024-06-26 15:58:04 +08:00
850815b9c6 AI配置提示 2024-06-26 13:38:18 +08:00
f2c35552b8 更新README.md 2024-06-26 13:36:23 +08:00
068434a5ec 更新README.md 2024-06-26 13:18:41 +08:00
68ab90915f 更新README.md 2024-06-26 13:17:13 +08:00
9e987337c3 更新README.md 2024-06-26 13:10:43 +08:00
5d95a3277c 文档调整 2024-06-26 13:04:23 +08:00
5c4154941a 错误信息语句不通顺 #6643 2024-06-25 13:51:21 +08:00
e7dfe5cdc3 更新issue要求 2024-06-24 15:43:17 +08:00
e016390f00 更新README.md 2024-06-24 15:35:30 +08:00
f69dd81b8b 更新README.md 2024-06-24 15:18:43 +08:00
2ec292e406 更新README.md 2024-06-24 15:16:18 +08:00
aeac0549f8 更新README.md 2024-06-24 15:13:48 +08:00
c53e217448 更新README.md 2024-06-24 15:01:53 +08:00
f2dfad1b15 更新README.md 2024-06-24 14:52:17 +08:00
2bed764621 更新README.md 2024-06-24 14:42:15 +08:00
2eea01bd37 更新README.md 2024-06-24 14:34:15 +08:00
c6f482b898 更新README.md 2024-06-24 14:11:34 +08:00
67b1e237bd 文档地址更新 2024-06-23 13:59:59 +08:00
3f74fc0778 JeecgBoot 3.7.0_all 版本发布(前端和后端合并一个仓库) 2024-06-23 11:33:41 +08:00
705 changed files with 27481 additions and 9196 deletions

4
.gitattributes vendored
View File

@ -1,5 +1,5 @@
*.js linguist-language=Java *.js linguist-language=Java
*.css linguist-language=Java *.css linguist-language=Java
*.html linguist-language=Java *.ts linguist-language=vue
*.vue linguist-language=Java *.html linguist-language=vue
*.sql linguist-language=Java *.sql linguist-language=Java

View File

@ -1,13 +1,16 @@
##### 版本号: ##### 版本号:
##### 问题描述: ##### 问题描述:
##### 错误截图: ##### 错误截图:
#### 友情提示: #### 友情提示:
- 未按格式要求发帖、描述过于简抽象的,会被直接删掉 - 未按格式要求发帖、描述过于简的,会被直接删掉;
- 请确保问题描述清楚,方便我们理解并一次性调查解决问题 - 描述问题请图文并茂,方便我们理解并快速定位问题;
- 如果使用的不是master请说明你使用的那个分支 - 如果使用的不是master请说明你使用的分支;

1
.gitignore vendored
View File

@ -13,4 +13,3 @@ os_del.cmd
os_del_doc.cmd os_del_doc.cmd
.svn .svn
derby.log derby.log
*.log

23
LICENSE
View File

@ -201,16 +201,13 @@
limitations under the License. limitations under the License.
In any case, you must not make any such use of this software as to develop software which may be considered competitive with this software. In any case, you must not make any such use of this software as to develop software which may be considered competitive with this software.
开源协议补充 JeecgBoot 是由 北京国炬信息技术有限公司 发行的软件。 总部位于北京地址中国·北京·朝阳区科荟前街1号院奥林佳泰大厦。邮箱jeecgos@163.com
JeecgBoot 是由 北京国炬信息技术有限公司 发行的软件。 总部位于北京地址中国·北京·朝阳区科荟前街1号院奥林佳泰大厦。邮箱jeecgos@163.com 本软件受适用的国家软件著作权法(包括国际条约)和开源协议 双重保护许可。
本软件受适用的国家软件著作权法(包括国际条约)和双重保护许可。
开源协议中文释意如下:
1.允许基于本平台软件开展业务系统开发 1.JeecgBoot开源版本无任何限制在遵循本开源协议条款下允许商用使用不会造成侵权行为
2.JeecgBoot底层依赖的非开源功能online lib依赖、仪表盘lib依赖等统一采用LGPL开源协议不二次改造、不拆分出jeecgboot之外使用就不产生侵权 2.允许基于本平台软件开展业务系统开发。
3.不得基于该平台软件的基础修改包装成一个与JeecgBoot平台软件功能类似的产品进行发布、销售或与JeecgBoot参与同类软件产品市场的竞争 3.在任何情况下,您不得使用本软件开发可能被认为与本软件竞争的软件
违反此条款属于侵权行为,须赔偿侵权经济损失,同时立即停止著作权侵权行为。
最终解释权归http://www.jeecg.com
总结在遵循Apache开源协议和开源协议补充条款下允许商用使用不会造成侵权行为
解释权归http://www.jeecg.com

View File

@ -7,13 +7,12 @@
JEECG BOOT Low Code Development Platform JEECG BOOT Low Code Development Platform
=============== ===============
当前最新版本: 3.7.0发布日期2024-06-17 Current version: 3.7.2 (Release date: 2024-12-12)
[![AUR](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg)](https://github.com/zhangdaiscott/jeecg-boot/blob/master/LICENSE) [![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/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.7.2-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 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) [![GitHub forks](https://img.shields.io/github/forks/zhangdaiscott/jeecg-boot.svg?style=social&label=Fork)](https://github.com/zhangdaiscott/jeecg-boot)
@ -39,9 +38,6 @@ Technical support
Problems or bugs in use can be found in [Making on the Issues](https://github.com/jeecgboot/JeecgBoot/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
##### Project description ##### Project description
@ -64,14 +60,11 @@ For the project
Jeecg-Boot low code development platform can be applied in the development of any J2EE project, especially for SAAS projects, enterprise information management system (MIS), internal office system (OA), enterprise resource planning system (ERP), customer relationship management system (CRM), etc. Its semi-intelligent manual Merge development method, Can significantly improve the development efficiency of more than 70%, greatly reduce the development cost. Jeecg-Boot low code development platform can be applied in the development of any J2EE project, especially for SAAS projects, enterprise information management system (MIS), internal office system (OA), enterprise resource planning system (ERP), customer relationship management system (CRM), etc. Its semi-intelligent manual Merge development method, Can significantly improve the development efficiency of more than 70%, greatly reduce the development cost.
Starts the project
Docker starts the project
----------------------------------- -----------------------------------
- [Docker starts the monomer background](https://help.jeecg.com/java/setup/docker/up.html) - [IDEA Quick start](https://help.jeecg.com/java/setup/idea/startup.html)
- [Docker starts the front-end](http://help.jeecg.com/publish/docker.html) - [Docker Quick start](https://help.jeecg.com/java/docker/quick.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)
@ -79,12 +72,14 @@ Technical documentation
----------------------------------- -----------------------------------
- Website [http://www.jeecg.com](http://www.jeecg.com) - Website [http://www.jeecg.com](http://www.jeecg.com)
- 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 ⑨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) - Demo [OnlineDemo](http://boot3.jeecg.com) | [APP](http://jeecg.com/appIndex)
> [please click obtain account password to obtain](http://jeecg.com/doc/demo) - Doc [http://help.jeecg.com](http://help.jeecg.com)
- Newbie guide [Quick start](http://www.jeecg.com/doc/quickstart) | [Q&A ](http://www.jeecg.com/doc/qa) | [1 minute experience](https://my.oschina.net/jeecg/blog/3083313)
- QQ group ⑩716488839、⑨808791225、⑧825232878、⑦791696430、⑥730954414(full)、683903138(full)、⑤860162132(full)、④774126647(full)、③816531124(full)、②769925425(full)、①284271917(full)
Star charts Star charts
@ -180,7 +175,7 @@ Technical Architecture:
#### Development Environment #### Development Environment
- Language: Java 8+ (less than 17) - Language: Java 8+ (17)
- IDE(JAVA) : IDEA (lombok plug-in must be installed) - IDE(JAVA) : IDEA (lombok plug-in must be installed)
@ -190,20 +185,20 @@ Technical Architecture:
- Cache: Redis - Cache: Redis
- Database: MySQL5.7 + & Oracle 11 g & Sqlserver2017 [More Databases](https://my.oschina.net/jeecg/blog/4905722) - Database: MySQL5.7 + [More Databases](https://my.oschina.net/jeecg/blog/4905722)
#### backend #### backend
- Basic framework: Spring Boot 2.6.14 - Basic framework: Spring Boot 2.7.18
- Microservice framework: Spring Cloud Alibaba 2021.0.1.0 - Microservice framework: Spring Cloud Alibaba 2021.0.1.0
- Persistence layer framework: MybatisPlus 3.5.1 - Persistence layer framework: MybatisPlus 3.5.3.2
- Report tool: JimuReport 1.5.8 - Report tool: JimuReport 1.9.1
- Security framework: Apache Shiro 1.10.0, Jwt 3.11.0 - Security framework: Apache Shiro 1.12.0, Jwt 3.11.0
- Microservice technology stack: Spring Cloud Alibaba, Nacos, Gateway, Sentinel, Skywalking - Microservice technology stack: Spring Cloud Alibaba, Nacos, Gateway, Sentinel, Skywalking
@ -218,6 +213,12 @@ Technical Architecture:
- TechnologyStack`Vue3.0+TypeScript+Vite+AntDesignVue+pinia+echarts` - TechnologyStack`Vue3.0+TypeScript+Vite+AntDesignVue+pinia+echarts`
#### Front-end environment requirements
* `Node.js 、npm 、pnpm`
* Node.js Version suggestion: `v20.15.0`
` ( Since Vite5 no longer supports EOL Node.js 14/16/17/19, Node.js 18/20 + is now required )`
#### Support library #### Support library
| database | support | | database | support |
@ -227,44 +228,29 @@ Technical Architecture:
| Sqlserver2017 | √ | | Sqlserver2017 | √ |
| PostgreSQL | √ | | PostgreSQL | √ |
| MariaDB | √ | | MariaDB | √ |
| 达梦、人大金仓 | √ | | 达梦 | √ |
| 人大金仓 | √ |
| TiDB | √ |
## Microservice solutions ## Microservice solutions
- 1. Service registration and discovery Nacos √
1. Service registration and discovery Nacos √ - 2. Nacos √
- 3. Route gateway gateway(Three loading modes) √
2. Nacos - 4. Distributed http feign
- 5. fuse degrade current limiting Sentinel √
3. Route gateway gateway(Three loading modes) - 6. Distributed files Minio and Alioss
- 7. Unified permission control
4. Distributed http feign - 8. Service monitoring SpringBootAdmin
- 9. link tracking Skywalking [reference document](https://help.jeecg.com/java/springcloud/super/skywarking.html)
5. fuse degrade current limiting Sentinel - 10. Messaging middleware RabbitMQ
- 11. Distributed task xxl-job √
6. Distributed files Minio and Alioss √ - 12. Distributed Transaction Seata
- 13. Distributed log Loki+grafana
7. Unified permission control - 14. Support docker-compose, k8s, jenkins
- 15. CAS SSO √
8. Service monitoring SpringBootAdmin - 16. Route traffic limiting
9. link tracking Skywalking [reference document](https://help.jeecg.com/java/springcloud/super/skywarking.html)
10. Messaging middleware RabbitMQ √
11. Distributed task xxl-job √
12. Distributed Transaction Seata
13. Distributed log elk + kafka
14. Support docker-compose, k8s, jenkins
15. CAS SSO √
16. Route traffic limiting √
#### Microservice architecture diagram #### Microservice architecture diagram
@ -273,157 +259,9 @@ Technical Architecture:
### Jeecg Boot product functionality blueprint ### Jeecg Boot product functionality blueprint
![功能蓝图](https://jeecgos.oss-cn-beijing.aliyuncs.com/upload/test/Jeecg-Boot-lantu202005_1590912449914.jpg "在这里输入图片标题") ![功能蓝图](https://jeecgos.oss-cn-beijing.aliyuncs.com/upload/test/Jeecg-Boot-lantu202005_1590912449914.jpg "在这里输入图片标题")
### quick start
- Microservice Development [Monomer upgrade to microservice](https://help.jeecg.com/java/springcloud/switchcloud/monomer.html)
- [Docker starts the micro-service background](https://help.jeecg.com/java/docker/springcloud.html)
### Function module
```
├─系统管理
│ ├─用户管理
│ ├─角色管理
│ ├─菜单管理
│ ├─权限设置(支持按钮权限、数据权限)
│ ├─表单权限(控制字段禁用、隐藏)
│ ├─部门管理
│ ├─我的部门(二级管理员)
│ └─字典管理
│ └─分类字典
│ └─系统公告
│ └─职务管理
│ └─通讯录
│ └─多租户管理
├─消息中心
│ ├─消息管理
│ ├─模板管理
├─代码生成器(低代码)
│ ├─代码生成器功能(一键生成前后端代码,生成后无需修改直接用,绝对是后端开发福音)
│ ├─代码生成器模板提供4套模板分别支持单表和一对多模型不同风格选择
│ ├─代码生成器模板生成代码自带excel导入导出
│ ├─查询过滤器(查询逻辑无需编码,系统根据页面配置自动生成)
│ ├─高级查询器(弹窗自动组合查询条件)
│ ├─Excel导入导出工具集成支持单表一对多 导入导出)
│ ├─平台移动自适应支持
├─系统监控
│ ├─Gateway路由网关
│ ├─性能扫描监控
│ │ ├─监控 Redis
│ │ ├─Tomcat
│ │ ├─jvm
│ │ ├─服务器信息
│ │ ├─请求追踪
│ │ ├─磁盘监控
│ ├─定时任务
│ ├─系统日志
│ ├─消息中心(支持短信、邮件、微信推送等等)
│ ├─数据日志(记录数据快照,可对比快照,查看数据变更情况)
│ ├─系统通知
│ ├─SQL监控
│ ├─swagger-ui(在线接口文档)
│─报表示例
│ ├─曲线图
│ └─饼状图
│ └─柱状图
│ └─折线图
│ └─面积图
│ └─雷达图
│ └─仪表图
│ └─进度条
│ └─排名列表
│ └─等等
│─大屏模板
│ ├─作战指挥中心大屏
│ └─物流服务中心大屏
│─常用示例
│ ├─自定义组件
│ ├─对象存储(对接阿里云)
│ ├─JVXETable示例各种复杂ERP布局示例
│ ├─单表模型例子
│ └─一对多模型例子
│ └─打印例子
│ └─一对多TAB例子
│ └─内嵌table例子
│ └─常用选择组件
│ └─异步树table
│ └─接口模拟测试
│ └─表格合计示例
│ └─异步树列表示例
│ └─一对多JEditable
│ └─JEditable组件示例
│ └─图片拖拽排序
│ └─图片翻页
│ └─图片预览
│ └─PDF预览
│ └─分屏功能
│─封装通用组件
│ ├─行编辑表格JEditableTable
│ └─省略显示组件
│ └─时间控件
│ └─高级查询
│ └─用户选择组件
│ └─报表组件封装
│ └─字典组件
│ └─下拉多选组件
│ └─选人组件
│ └─选部门组件
│ └─通过部门选人组件
│ └─封装曲线、柱状图、饼状图、折线图等等报表的组件(经过封装,使用简单)
│ └─在线code编辑器
│ └─上传文件组件
│ └─验证码组件
│ └─树列表组件
│ └─表单禁用组件
│ └─等等
│─更多页面模板
│ ├─各种高级表单
│ ├─各种列表效果
│ └─结果页面
│ └─异常页面
│ └─个人页面
├─高级功能
│ ├─系统编码规则
│ ├─提供单点登录CAS集成方案
│ ├─提供APP发布方案
│ ├─集成Websocket消息通知机制
├─Online在线开发(低代码)
│ ├─Online在线表单 - 功能已开放
│ ├─Online代码生成器 - 功能已开放
│ ├─Online在线报表 - 功能已开放
│ ├─Online在线图表(未开源)
│ ├─Online图表模板配置(未开源)
│ ├─Online布局设计(未开源)
│ ├─多数据源管理 - 功能已开放
├─积木报表设计器(低代码)
│ ├─打印设计器
│ ├─数据报表设计
│ ├─图形报表设计支持echart
│ ├─大屏设计器(未开源)
│─流程模块功能 (未开源)
│ ├─流程设计器
│ ├─表单设计器
├─大屏设计器
├─门户设计/仪表盘设计器
│ └─我的任务
│ └─历史流程
│ └─历史流程
│ └─流程实例管理
│ └─流程监听管理
│ └─流程表达式
│ └─我发起的流程
│ └─我的抄送
│ └─流程委派、抄送、跳转
│ └─。。。
│─OA办公组件 (未开源)
│ ├─更多功能
│ └─。。。
└─其他模块
└─更多功能开发中。。
```
### Effect of system ### Effect of system
@ -470,10 +308,22 @@ Technical Architecture:
![](https://oscimg.oschina.net/oscnet/up-7f83b25159663686d67ed080eb16068c3b4.png) ![](https://oscimg.oschina.net/oscnet/up-7f83b25159663686d67ed080eb16068c3b4.png)
##### dashboard Designer ##### dashboard Designer
![](https://oscimg.oschina.net/oscnet/up-9c9d41288c31398d76b390bdd400f13a582.png)
![](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/darg20240726105556.png)
![](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/drag20240724135626.png)
![](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/drag20240724135619.png)
![](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/drag20240724135630.png)
![](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/drag20240726105547.png)
![](https://oscimg.oschina.net/oscnet/up-fad98d42b2cf92f92a903c9cff7579f18ec.png) ![](https://oscimg.oschina.net/oscnet/up-fad98d42b2cf92f92a903c9cff7579f18ec.png)
##### report Designer ##### report Designer
![](https://oscimg.oschina.net/oscnet/up-64648de000851f15f6c7b9573d107ebb5f8.png) ![](https://oscimg.oschina.net/oscnet/up-64648de000851f15f6c7b9573d107ebb5f8.png)

332
README.md
View File

@ -2,15 +2,14 @@
JeecgBoot 低代码开发平台 JeecgBoot 低代码开发平台
=============== ===============
当前最新版本: 3.7.0发布日期2024-06-17 当前最新版本: 3.7.2发布日期2024-12-12
[![AUR](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg)](https://github.com/zhangdaiscott/jeecg-boot/blob/master/LICENSE) [![AUR](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg)](https://github.com/jeecgboot/JeecgBoot/blob/master/LICENSE)
[![](https://img.shields.io/badge/Author-北京国炬软件-orange.svg)](http://jeecg.com/aboutusIndex) [![](https://img.shields.io/badge/Author-北京国炬软件-orange.svg)](http://guojusoft.com)
[![](https://img.shields.io/badge/Blog-官方博客-blue.svg)](https://jeecg.blog.csdn.net) [![](https://img.shields.io/badge/version-3.7.2-brightgreen.svg)](https://github.com/jeecgboot/JeecgBoot)
[![](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/jeecgboot/JeecgBoot)
[![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/jeecgboot/JeecgBoot)
[![GitHub forks](https://img.shields.io/github/forks/zhangdaiscott/jeecg-boot.svg?style=social&label=Fork)](https://github.com/zhangdaiscott/jeecg-boot)
@ -19,7 +18,7 @@ JeecgBoot 低代码开发平台
<h3 align="center">Java Low Code Platform for Enterprise web applications</h3> <h3 align="center">Java Low Code Platform for Enterprise web applications</h3>
JeecgBoot 是一款基于代码生成器的`低代码开发平台`!前后端分离架构 SpringBoot2.x和3.xSpringCloudAnt Design&VueMybatis-plusShiroJWT支持微服务。强大的代码生成器让前后端代码一键生成实现低代码开发! JeecgBoot 引领新的低代码开发模式(OnlineCoding-> 代码生成器-> 手工MERGE) 帮助解决Java项目70%的重复工作,让开发更多关注业务。既能快速提高效率,节省研发成本,同时又不失灵活性! JeecgBoot 是一款基于代码生成器的`低代码开发平台`!前后端分离架构 SpringBoot2.x和3.xSpringCloudAnt Design Vue3Mybatis-plusShiroJWT支持微服务。强大的代码生成器让前后端代码一键生成实现低代码开发! JeecgBoot集成AI模型能力引领新的低代码开发模式(OnlineCoding-> 代码生成器-> 手工MERGE) 帮助解决Java项目70%的重复工作,让开发更多关注业务。既能快速提高效率,节省研发成本,同时又不失灵活性!
JeecgBoot 提供了一系列`低代码模块`,实现在线开发`真正的零代码`Online表单开发、Online报表、报表配置能力、在线图表设计、仪表盘设计、大屏设计、移动配置能力、表单设计器、在线设计流程、流程自动化配置、插件能力可插拔等等 JeecgBoot 提供了一系列`低代码模块`,实现在线开发`真正的零代码`Online表单开发、Online报表、报表配置能力、在线图表设计、仪表盘设计、大屏设计、移动配置能力、表单设计器、在线设计流程、流程自动化配置、插件能力可插拔等等
@ -34,68 +33,137 @@ JeecgBoot 提供了一系列`低代码模块`,实现在线开发`真正的零
Jeecg-Boot低代码开发平台可以应用在任何J2EE项目的开发中支持信创国产化默认适配达梦和人大金仓。尤其适合SAAS项目、企业信息管理系统MIS、内部办公系统OA、企业资源计划系统ERP、客户关系管理系统CRM其半智能手工Merge的开发方式可以显著提高开发效率70%以上,极大降低开发成本。 Jeecg-Boot低代码开发平台可以应用在任何J2EE项目的开发中支持信创国产化默认适配达梦和人大金仓。尤其适合SAAS项目、企业信息管理系统MIS、内部办公系统OA、企业资源计划系统ERP、客户关系管理系统CRM其半智能手工Merge的开发方式可以显著提高开发效率70%以上,极大降低开发成本。
#### 项目说明 #### 项目说明
| 项目名 | 说明 | | 项目名 | 说明 |
|--------------------|------------------------| |--------------------|------------------------|
| `jeecg-boot` | 后端源码JAVASpringBoot微服务架构 | | `jeecg-boot` | 后端源码JAVASpringBoot微服务架构 |
| `jeecgboot-vue3` | 前端源码VUE3vue3+vite5+ts最新技术栈 | | `jeecgboot-vue3` | 前端源码VUE3vue3+vite5+ts最新技术栈 |
| `jeecg-uniapp` | APP框架,一份代码多终端适配支持APP、小程序、H5 | | `jeecg-uniapp` | [配套APP框架](https://github.com/jeecgboot/jeecg-uniapp) 适配多个终端支持APP、小程序、H5 |
其他源码 开源协议说明
----------------------------------- -----------------------------------
- APP源码地址https://github.com/jeecgboot/jeecg-uniapp JeecgBoot开源版本底层完全开源可以自主开发遵循Apache2.0协议,详细见 https://github.com/jeecgboot/JeecgBoot#Apache-2.0-1-ov-file
开源协议中文释意如下:
技术支持 - 1.JeecgBoot开源版本无任何限制在遵循本开源协议条款下允许商用使用不会造成侵权行为。
----------------------------------- - 2.允许基于本平台软件开展业务系统开发。
- 3.在任何情况下,您不得使用本软件开发可能被认为与本软件竞争的软件。
关闭gitee的issue通道使用中遇到问题或者BUG可以在 [Github上提Issues](https://github.com/jeecgboot/JeecgBoot/issues/new) - 4.针对企业用户我们也提供“企业级版本”,详细见 https://jeecg.com/vip
快速启动项目
-----------------------------------
- [前端项目快速启动](http://help.jeecg.com/setup/startup.html)
- [通过IDEA启动前后端项目](https://help.jeecg.com/java/setup/idea/startup.html)
Docker启动项目
-----------------------------------
- [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://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
- 在线演示 [在线演示](http://boot3.jeecg.com) | [APP演示](http://jeecg.com/appIndex) - 在线演示 [在线演示](http://boot3.jeecg.com) | [APP演示](http://jeecg.com/appIndex)
> 演示系统的登录账号密码,请点击 [获取账号密码](http://jeecg.com/doc/demo) 获取 - 快速体验: [一分钟体验低代码](https://jeecg.blog.csdn.net/article/details/106079007?spm=1001.2014.3001.5502 "一分钟体验零代码") | [在线体验零代码](https://app.qiaoqiaoyun.com/myapps/index "在线体验零代码")
> - 开发文档: [https://help.jeecg.com](https://help.jeecg.com)
- QQ交流群 ⑨808791225、⑧825232878、⑦791696430(满)、⑥730954414(满)、683903138(满)、⑤860162132(满)、④774126647(满)、③816531124(满)、②769925425(满)、①284271917(满) - 反馈问题: [在Github上提Issues](https://github.com/jeecgboot/JeecgBoot/issues/new)
- 新手指南: [快速入门](http://www.jeecg.com/doc/quickstart) | [入门视频](http://jeecg.com/doc/video)
- QQ交流群 ⑩716488839、⑨808791225(满)、其他(满)
启动项目
-----------------------------------
- [IDEA启动前后端项目](https://help.jeecg.com/java/setup/idea/startup.html)
- [Docker一键启动前后端](https://help.jeecg.com/java/docker/quick.html)
技术架构:
-----------------------------------
#### 后端
- IDE建议 IDEA (必须安装lombok插件 )
- 语言Java 8+ (支持17)
- 依赖管理Maven
- 基础框架Spring Boot 2.7.18
- 微服务框架: Spring Cloud Alibaba 2021.0.1.0
- 持久层框架MybatisPlus 3.5.3.2
- 报表工具: JimuReport 1.9.1
- 安全框架Apache Shiro 1.12.0Jwt 3.11.0
- 微服务技术栈Spring Cloud Alibaba、Nacos、Gateway、Sentinel、Skywalking
- 数据库连接池阿里巴巴Druid 1.1.22
- 日志打印logback
- 缓存Redis
- 其他autopoi, fastjsonpoiSwagger-uiquartz, lombok简化代码等。
- 默认数据库脚本MySQL5.7+
- [其他数据库,需要自己转](https://my.oschina.net/jeecg/blog/4905722)
#### 前端
- 前端IDE建议WebStorm、Vscode
- 采用 Vue3.0+TypeScript+Vite5+Ant-Design-Vue等新技术方案包括二次封装组件、utils、hooks、动态菜单、权限校验、按钮级别权限控制等功能
- 最新技术栈Vue3.0 + TypeScript + Vite5 + ant-design-vue4 + pinia + echarts + unocss + vxe-table + qiankun + es6
- 依赖管理node、npm、pnpm
#### 前端环境要求
* 本地环境安装 `Node.js 、npm 、pnpm`
* Node.js 版本建议`v20.15.0`,要求`Node 20+` 版本以上
` ( 因为Vite5 不再支持已 EOL 的 Node.js 14 / 16 / 17 / 19现在需要 Node.js 18 / 20+ )`
#### 支持库
| 数据库 | 支持 |
| --- | --- |
| MySQL | √ |
| Oracle11g | √ |
| Sqlserver2017 | √ |
| PostgreSQL | √ |
| MariaDB | √ |
| MariaDB | √ |
| 达梦 | √ |
| 人大金仓 | √ |
| TiDB | √ |
## 微服务解决方案
- 1、服务注册和发现 Nacos √
- 2、统一配置中心 Nacos √
- 3、路由网关 gateway(三种加载方式) √
- 4、分布式 http feign √
- 5、熔断降级限流 Sentinel √
- 6、分布式文件 Minio、阿里OSS √
- 7、统一权限控制 JWT + Shiro √
- 8、服务监控 SpringBootAdmin√
- 9、链路跟踪 Skywalking [参考文档](https://help.jeecg.com/java/springcloud/super/skywarking.html)
- 10、消息中间件 RabbitMQ √
- 11、分布式任务 xxl-job √
- 12、分布式事务 Seata
- 13、轻量分布式日志 Loki+grafana套件
- 14、支持 docker-compose、k8s、jenkins
- 15、CAS 单点登录 √
- 16、路由限流 √
#### 微服务方式启动
- [单体快速切换微服务](https://help.jeecg.com/java/springcloud/switchcloud/monomer.html)
- [Docker一键启动微服务前后端](https://help.jeecg.com/java/docker/quickcloud.html)
#### 微服务架构图
![微服务架构图](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/jeecgboot_springcloud2022.png "在这里输入图片标题")
为什么选择JeecgBoot? 为什么选择JeecgBoot?
----------------------------------- -----------------------------------
* 1.采用最新主流前后分离框架Springboot+Mybatis+antd容易上手; 代码生成器依赖性低,灵活的扩展能力,可快速实现二次开发; * 1.采用最新主流前后分离框架Springboot+Mybatis+antd+vue3),容易上手; 代码生成器依赖性低,灵活的扩展能力,可快速实现二次开发;
* 2.支持微服务SpringCloud Alibaba(Nacos、Gateway、Sentinel、Skywalking),提供切换机制支持单体和微服务自由切换 * 2.支持微服务SpringCloud Alibaba(Nacos、Gateway、Sentinel、Skywalking),提供切换机制支持单体和微服务自由切换
* 3.开发效率高,采用代码生成器,单表、树列表、一对多、一对一等数据模型,增删改查功能一键生成,菜单配置直接使用; * 3.开发效率高,采用代码生成器,单表、树列表、一对多、一对一等数据模型,增删改查功能一键生成,菜单配置直接使用;引入AI能力支持自动建表等功能
* 4.代码生成器提供强大模板机制,支持自定义模板,目前提供四套风格模板(单表两套、树模型一套、一对多三套) * 4.代码生成器提供强大模板机制,支持自定义模板,目前提供四套风格模板(单表两套、树模型一套、一对多三套)
* 5.代码生成器非常智能在线业务建模、在线配置、所见即所得支持23种类控件一键生成前后端代码大幅度提升开发效率不再为重复工作发愁。 * 5.代码生成器非常智能在线业务建模、在线配置、所见即所得支持23种类控件一键生成前后端代码大幅度提升开发效率不再为重复工作发愁。
* 6.低代码能力Online在线表单无需编码通过在线配置表单实现表单的增删改查支持单表、树、一对多、一对一等模型实现人人皆可编码 * 6.低代码能力Online在线表单无需编码通过在线配置表单实现表单的增删改查支持单表、树、一对多、一对一等模型实现人人皆可编码
@ -111,7 +179,7 @@ Docker启动项目
* 16.页面校验自动生成(必须输入、数字校验、金额校验、时间空间等); * 16.页面校验自动生成(必须输入、数字校验、金额校验、时间空间等);
* 17.支持SAAS服务模式提供SaaS多租户架构方案。 * 17.支持SAAS服务模式提供SaaS多租户架构方案。
* 18.分布式文件服务集成minio、阿里OSS等优秀的第三方提供便捷的文件上传与管理同时也支持本地存储。 * 18.分布式文件服务集成minio、阿里OSS等优秀的第三方提供便捷的文件上传与管理同时也支持本地存储。
* 19.主流数据库兼容一套代码完全兼容Mysql、Postgresql、Oracle、Sqlserver、MariaDB、达梦等主流数据库。 * 19.主流数据库兼容一套代码完全兼容Mysql、Postgresql、Oracle、Sqlserver、MariaDB、达梦、人大金仓等主流数据库。
* 20.集成工作流flowable并实现了只需在页面配置流程转向可极大的简化bpm工作流的开发用bpm的流程设计器画出了流程走向一个工作流基本就完成了只需写很少量的java代码 * 20.集成工作流flowable并实现了只需在页面配置流程转向可极大的简化bpm工作流的开发用bpm的流程设计器画出了流程走向一个工作流基本就完成了只需写很少量的java代码
* 21.低代码能力在线流程设计采用开源flowable流程引擎实现在线画流程,自定义表单,表单挂靠,业务流转 * 21.低代码能力在线流程设计采用开源flowable流程引擎实现在线画流程,自定义表单,表单挂靠,业务流转
* 22.多数据源:及其简易的使用方式,在线配置数据源配置,便捷的从其他数据抓取数据; * 22.多数据源:及其简易的使用方式,在线配置数据源配置,便捷的从其他数据抓取数据;
@ -134,103 +202,8 @@ Docker启动项目
* 39.支持菜单动态路由 * 39.支持菜单动态路由
* 40.权限控制采用 RBACRole-Based Access Control基于角色的访问控制 * 40.权限控制采用 RBACRole-Based Access Control基于角色的访问控制
* 41.提供新行编辑表格JVXETable轻松满足各种复杂ERP布局拥有更高的性能、更灵活的扩展、更强大的功能 * 41.提供新行编辑表格JVXETable轻松满足各种复杂ERP布局拥有更高的性能、更灵活的扩展、更强大的功能
* 42.提供仪表盘设计器,类大屏设计支持移动端,免费的数据可视化设计工具,支持丰富的数据源连接,能够通过拖拉拽方式快速制作图表和门户设计;目前支持多种图表类型:柱形图、折线图、散点图、饼图、环形图、面积图、漏斗图、进度图、仪表盘、雷达图、地图等等;
技术架构:
-----------------------------------
#### 开发环境
- 语言Java 8+ (小于17)
- IDE(JAVA) IDEA (必须安装lombok插件 )
- IDE(前端) Vscode、WebStorm、IDEA
- 依赖管理Maven
- 缓存Redis
- 数据库脚本MySQL5.7+ (其他数据库,[需要自己转](https://my.oschina.net/jeecg/blog/4905722)
#### 后端
- 基础框架Spring Boot 2.6.14
- 微服务框架: Spring Cloud Alibaba 2021.0.1.0
- 持久层框架MybatisPlus 3.5.1
- 报表工具: JimuReport 1.5.8
- 安全框架Apache Shiro 1.10.0Jwt 3.11.0
- 微服务技术栈Spring Cloud Alibaba、Nacos、Gateway、Sentinel、Skywalking
- 数据库连接池阿里巴巴Druid 1.1.22
- 日志打印logback
- 其他autopoi, fastjsonpoiSwagger-uiquartz, lombok简化代码等。
#### 前端
- 技术栈:`Vue3.0 + TypeScript + Vite5 + ant-design-vue4 + pinia + echarts + unocss + vxe-table + qiankun + es6` 等最新技术栈
#### 支持库
| 数据库 | 支持 |
| --- | --- |
| MySQL | √ |
| Oracle11g | √ |
| Sqlserver2017 | √ |
| PostgreSQL | √ |
| MariaDB | √ |
| 达梦、人大金仓 | √ |
## 微服务解决方案
1、服务注册和发现 Nacos √
2、统一配置中心 Nacos √
3、路由网关 gateway(三种加载方式) √
4、分布式 http feign √
5、熔断降级限流 Sentinel √
6、分布式文件 Minio、阿里OSS √
7、统一权限控制 JWT + Shiro √
8、服务监控 SpringBootAdmin√
9、链路跟踪 Skywalking [参考文档](https://help.jeecg.com/java/springcloud/super/skywarking.html)
10、消息中间件 RabbitMQ √
11、分布式任务 xxl-job √
12、分布式事务 Seata
13、分布式日志 elk + kafka
14、支持 docker-compose、k8s、jenkins
15、CAS 单点登录 √
16、路由限流 √
#### 微服务架构图
![微服务架构图](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/jeecgboot_springcloud2022.png "在这里输入图片标题")
### Jeecg Boot 产品功能蓝图 ### Jeecg Boot 产品功能蓝图
![功能蓝图](https://jeecgos.oss-cn-beijing.aliyuncs.com/upload/test/Jeecg-Boot-lantu202005_1590912449914.jpg "在这里输入图片标题") ![功能蓝图](https://jeecgos.oss-cn-beijing.aliyuncs.com/upload/test/Jeecg-Boot-lantu202005_1590912449914.jpg "在这里输入图片标题")
@ -238,6 +211,20 @@ Docker启动项目
### 分支说明
> 主干master更稳定如果你对最新技术栈无要求建议采用主干
#### springboot3分支
- 源码地址https://github.com/jeecgboot/JeecgBoot/tree/springboot3
- 架构说明升级Spring Boot3 & JDK 17 + Undertow + springdoc + fastjson2
#### springboot3_sas分支
- 源码地址https://github.com/jeecgboot/JeecgBoot/tree/springboot3_sas
- 架构说明在springboot3分支基础上采用SpringAuthorizationServer替换Shiro
### 功能模块 ### 功能模块
``` ```
├─Online在线开发(低代码) ├─Online在线开发(低代码)
@ -378,38 +365,6 @@ Docker启动项目
后台目录结构
-----------------------------------
```
项目结构
├─jeecg-boot-parent父POM 项目依赖、modules组织
│ ├─jeecg-boot-base-core共通模块 工具类、config、权限、查询过滤器、注解等
│ ├─jeecg-module-demo 示例代码
│ ├─jeecg-module-system System系统管理目录
│ │ ├─jeecg-system-biz System系统管理权限等功能
│ │ ├─jeecg-system-start System单体启动项目(8080
│ │ ├─jeecg-system-api System系统管理模块对外api
│ │ │ ├─jeecg-system-cloud-api System模块对外提供的微服务接口
│ │ │ ├─jeecg-system-local-api System模块对外提供的单体接口
│ ├─jeecg-server-cloud --微服务模块
├─jeecg-cloud-gateway --微服务网关模块(9999)
├─jeecg-cloud-nacos --Nacos服务模块(8848)
├─jeecg-system-cloud-start --System微服务启动项目(7001)
├─jeecg-demo-cloud-start --Demo微服务启动项目(7002)
├─jeecg-visual
├─jeecg-cloud-monitor --微服务监控模块 (9111)
├─jeecg-cloud-xxljob --微服务xxljob定时任务服务端 (9080)
├─jeecg-cloud-sentinel --sentinel服务端 (9000)
├─jeecg-cloud-test -- 微服务测试示例(各种例子)
├─jeecg-cloud-test-more -- 微服务测试示例feign、熔断降级、xxljob、分布式锁
├─jeecg-cloud-test-rabbitmq -- 微服务测试示例rabbitmq
├─jeecg-cloud-test-seata -- 微服务测试示例seata分布式事务
├─jeecg-cloud-test-shardingsphere -- 微服务测试示例(分库分表)
```
### 系统效果 ### 系统效果
##### PC端 ##### PC端
@ -435,10 +390,20 @@ Docker启动项目
##### 仪表盘设计器 ##### 仪表盘设计器
![](https://oscimg.oschina.net/oscnet/up-9c9d41288c31398d76b390bdd400f13a582.png)
![](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/darg20240726105556.png)
![](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/drag20240724135626.png)
![](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/drag20240724135619.png)
![](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/drag20240724135630.png)
![](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/drag20240726105547.png)
![](https://oscimg.oschina.net/oscnet/up-fad98d42b2cf92f92a903c9cff7579f18ec.png) ![](https://oscimg.oschina.net/oscnet/up-fad98d42b2cf92f92a903c9cff7579f18ec.png)
##### 报表设计器 ##### 报表设计器
![](https://oscimg.oschina.net/oscnet/up-64648de000851f15f6c7b9573d107ebb5f8.png) ![](https://oscimg.oschina.net/oscnet/up-64648de000851f15f6c7b9573d107ebb5f8.png)
@ -521,11 +486,4 @@ Docker启动项目
如果觉得还不错,请作者喝杯咖啡吧 ☺ 如果觉得还不错,请作者喝杯咖啡吧 ☺
![](https://static.oschina.net/uploads/img/201903/08155608_0EFX.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">

135
docker-compose-cloud.yml Normal file
View File

@ -0,0 +1,135 @@
version: '2'
services:
jeecg-boot-mysql:
build:
context: ./jeecg-boot/db
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_ROOT_HOST: '%'
TZ: Asia/Shanghai
restart: always
container_name: jeecg-boot-mysql
image: jeecg-boot-mysql
command:
--character-set-server=utf8mb4
--collation-server=utf8mb4_general_ci
--explicit_defaults_for_timestamp=true
--lower_case_table_names=1
--max_allowed_packet=128M
--default-authentication-plugin=caching_sha2_password
ports:
- 3306:3306
networks:
- jeecg-boot
jeecg-boot-redis:
image: registry.cn-hangzhou.aliyuncs.com/jeecgdocker/redis:5.0
ports:
- 6379:6379
restart: always
hostname: jeecg-boot-redis
container_name: jeecg-boot-redis
networks:
- jeecg-boot
jeecg-boot-nacos:
restart: always
build:
context: ./jeecg-boot/jeecg-server-cloud/jeecg-cloud-nacos
ports:
- 8848:8848
container_name: jeecg-boot-nacos
depends_on:
- jeecg-boot-mysql
hostname: jeecg-boot-nacos
networks:
- jeecg-boot
jeecg-boot-system:
depends_on:
- jeecg-boot-nacos
build:
context: ./jeecg-boot/jeecg-server-cloud/jeecg-system-cloud-start
container_name: jeecg-system-start
hostname: jeecg-boot-system
restart: on-failure
environment:
- TZ=Asia/Shanghai
networks:
- jeecg-boot
jeecg-boot-demo:
depends_on:
- jeecg-boot-nacos
build:
context: ./jeecg-boot/jeecg-server-cloud/jeecg-demo-cloud-start
container_name: jeecg-demo-start
hostname: jeecg-boot-demo
restart: on-failure
environment:
- TZ=Asia/Shanghai
networks:
- jeecg-boot
jeecg-boot-gateway:
restart: on-failure
build:
context: ./jeecg-boot/jeecg-server-cloud/jeecg-cloud-gateway
ports:
- 9999:9999
depends_on:
- jeecg-boot-nacos
- jeecg-boot-system
container_name: jeecg-boot-gateway
hostname: jeecg-boot-gateway
networks:
- jeecg-boot
# jeecg-boot-rabbitmq:
# image: rabbitmq:3.7.7-management
# ports:
# - 5672:5672
# - 15672:15672
# restart: always
# container_name: jeecg-boot-rabbitmq
# hostname: jeecg-boot-rabbitmq
# environment:
# RABBITMQ_DEFAULT_USER: guest
# RABBITMQ_DEFAULT_PASS: guest
# jeecg-boot-sentinel:
# restart: on-failure
# build:
# context: ./jeecg-visual/jeecg-cloud-sentinel
# ports:
# - 9000:9000
# depends_on:
# - jeecg-boot-nacos
# - jeecg-boot-demo
# - jeecg-boot-system
# - jeecg-boot-gateway
# container_name: jeecg-boot-sentinel
# hostname: jeecg-boot-sentinel
#
# jeecg-boot-xxljob:
# build:
# context: ./jeecg-visual/jeecg-cloud-xxljob
# ports:
# - 9080:9080
# container_name: jeecg-boot-xxljob
# hostname: jeecg-boot-xxljob
jeecg-vue:
build:
context: ./jeecgboot-vue3
container_name: jeecgboot-vue3-nginx
image: jeecgboot-vue3
depends_on:
- jeecg-boot-system
networks:
- jeecg-boot
ports:
- 80:80
networks:
jeecg-boot:
name: jeecg_boot

View File

@ -2,13 +2,14 @@ version: '2'
services: services:
jeecg-boot-mysql: jeecg-boot-mysql:
build: build:
context: ../db context: ./jeecg-boot/db
environment: environment:
MYSQL_ROOT_PASSWORD: root MYSQL_ROOT_PASSWORD: root
MYSQL_ROOT_HOST: '%' MYSQL_ROOT_HOST: '%'
TZ: Asia/Shanghai TZ: Asia/Shanghai
restart: always restart: always
container_name: jeecg-boot-mysql container_name: jeecg-boot-mysql
image: jeecg-boot-mysql
command: command:
--character-set-server=utf8mb4 --character-set-server=utf8mb4
--collation-server=utf8mb4_general_ci --collation-server=utf8mb4_general_ci
@ -22,28 +23,41 @@ services:
- jeecg-boot - jeecg-boot
jeecg-boot-redis: jeecg-boot-redis:
image: redis:5.0 image: registry.cn-hangzhou.aliyuncs.com/jeecgdocker/redis:5.0
ports: ports:
- 6379:6379 - 6379:6379
restart: always restart: always
container_name: jeecg-boot-redis
hostname: jeecg-boot-redis hostname: jeecg-boot-redis
container_name: jeecg-boot-redis
networks: networks:
- jeecg-boot - jeecg-boot
jeecg-boot-system:
build:
context: ./jeecg-boot/jeecg-module-system/jeecg-system-start
restart: on-failure
depends_on:
- jeecg-boot-mysql
- jeecg-boot-redis
container_name: jeecg-boot-system
image: jeecg-boot-system
hostname: jeecg-boot-system
ports:
- 8080:8080
networks:
- jeecg-boot
jeecg-vue:
build:
context: ./jeecgboot-vue3
container_name: jeecgboot-vue3-nginx
image: jeecgboot-vue3
depends_on:
- jeecg-boot-system
networks:
- jeecg-boot
ports:
- 80:80
networks: networks:
jeecg-boot: jeecg-boot:
name: jeecg_boot name: jeecg_boot
# jeecg-boot-rabbitmq:
# image: rabbitmq:3.7.7-management
# ports:
# - 5672:5672
# - 15672:15672
# restart: always
# container_name: jeecg-boot-rabbitmq
# hostname: jeecg-boot-rabbitmq
# environment:
# RABBITMQ_DEFAULT_USER: guest
# RABBITMQ_DEFAULT_PASS: guest

View File

@ -13,4 +13,3 @@ os_del.cmd
os_del_doc.cmd os_del_doc.cmd
.svn .svn
derby.log derby.log
*.log

View File

@ -201,16 +201,13 @@
limitations under the License. limitations under the License.
In any case, you must not make any such use of this software as to develop software which may be considered competitive with this software. In any case, you must not make any such use of this software as to develop software which may be considered competitive with this software.
开源协议补充 JeecgBoot 是由 北京国炬信息技术有限公司 发行的软件。 总部位于北京地址中国·北京·朝阳区科荟前街1号院奥林佳泰大厦。邮箱jeecgos@163.com
JeecgBoot 是由 北京国炬信息技术有限公司 发行的软件。 总部位于北京地址中国·北京·朝阳区科荟前街1号院奥林佳泰大厦。邮箱jeecgos@163.com 本软件受适用的国家软件著作权法(包括国际条约)和开源协议 双重保护许可。
本软件受适用的国家软件著作权法(包括国际条约)和双重保护许可。
开源协议中文释意如下:
1.允许基于本平台软件开展业务系统开发 1.JeecgBoot开源版本无任何限制在遵循本开源协议条款下允许商用使用不会造成侵权行为
2.JeecgBoot底层依赖的非开源功能online lib依赖、仪表盘lib依赖等统一采用LGPL开源协议不二次改造、不拆分出jeecgboot之外使用就不产生侵权 2.允许基于本平台软件开展业务系统开发。
3.不得基于该平台软件的基础修改包装成一个与JeecgBoot平台软件功能类似的产品进行发布、销售或与JeecgBoot参与同类软件产品市场的竞争 3.在任何情况下,您不得使用本软件开发可能被认为与本软件竞争的软件
违反此条款属于侵权行为,须赔偿侵权经济损失,同时立即停止著作权侵权行为。
最终解释权归http://www.jeecg.com
总结在遵循Apache开源协议和开源协议补充条款下允许商用使用不会造成侵权行为
解释权归http://www.jeecg.com

165
jeecg-boot/README.md Normal file
View File

@ -0,0 +1,165 @@
JeecgBoot 低代码开发平台
===============
当前最新版本: 3.7.2发布日期2024-12-12
[![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/version-3.7.2-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)
项目介绍
-----------------------------------
<h3 align="center">Java Low Code Platform for Enterprise web applications</h3>
JeecgBoot 是一款基于代码生成器的`低代码开发平台`!前后端分离架构 SpringBoot2.x和3.xSpringCloudAnt Design Vue3Mybatis-plusShiroJWT支持微服务。强大的代码生成器让前后端代码一键生成实现低代码开发! JeecgBoot 引领新的低代码开发模式(OnlineCoding-> 代码生成器-> 手工MERGE) 帮助解决Java项目70%的重复工作,让开发更多关注业务。既能快速提高效率,节省研发成本,同时又不失灵活性!
#### 项目说明
| 项目名 | 说明 |
|--------------------|------------------------|
| `jeecg-boot` | 后端源码JAVASpringBoot微服务架构 |
| `jeecgboot-vue3` | 前端源码VUE3vue3+vite5+ts最新技术栈 |
技术文档
-----------------------------------
- 官方网站: [http://www.jeecg.com](http://www.jeecg.com)
- 新手指南: [快速入门](http://www.jeecg.com/doc/quickstart)
- QQ交流群 ⑩716488839、⑨808791225、其他(满)
- 在线演示 [在线演示](http://boot3.jeecg.com) | [APP演示](http://jeecg.com/appIndex)
> 演示系统的登录账号密码,请点击 [获取账号密码](http://jeecg.com/doc/demo) 获取
启动项目
-----------------------------------
- [IDEA启动前后端项目](https://help.jeecg.com/java/setup/idea/startup.html)
- [Docker一键启动前后端](https://help.jeecg.com/java/docker/quick.html)
微服务启动
-----------------------------------
- [单体快速切换微服务](https://help.jeecg.com/java/springcloud/switchcloud/monomer.html)
- [Docker启动微服务后台](https://help.jeecg.com/java/docker/springcloud.html)
技术架构:
-----------------------------------
#### 后端
- IDE建议 IDEA (必须安装lombok插件 )
- 语言Java 8+ (支持17)
- 依赖管理Maven
- 基础框架Spring Boot 2.7.18
- 微服务框架: Spring Cloud Alibaba 2021.0.1.0
- 持久层框架MybatisPlus 3.5.3.2
- 报表工具: JimuReport 1.8.1
- 安全框架Apache Shiro 1.12.0Jwt 3.11.0
- 微服务技术栈Spring Cloud Alibaba、Nacos、Gateway、Sentinel、Skywalking
- 数据库连接池阿里巴巴Druid 1.1.22
- 日志打印logback
- 缓存Redis
- 其他autopoi, fastjsonpoiSwagger-uiquartz, lombok简化代码等。
- 默认数据库脚本MySQL5.7+
- [其他数据库,需要自己转](https://my.oschina.net/jeecg/blog/4905722)
#### 前端
- 前端IDE建议WebStorm、Vscode
- 采用 Vue3.0+TypeScript+Vite+Ant-Design-Vue等新技术方案包括二次封装组件、utils、hooks、动态菜单、权限校验、按钮级别权限控制等功能
- 最新技术栈Vue3.0 + TypeScript + Vite5 + ant-design-vue4 + pinia + echarts + unocss + vxe-table + qiankun + es6
- 依赖管理node、npm、pnpm
#### 支持库
| 数据库 | 支持 |
| --- | --- |
| MySQL | √ |
| Oracle11g | √ |
| Sqlserver2017 | √ |
| PostgreSQL | √ |
| MariaDB | √ |
| 达梦 | √ |
| 人大金仓 | √ |
| TiDB | √ |
## 微服务解决方案
- 1、服务注册和发现 Nacos √
- 2、统一配置中心 Nacos √
- 3、路由网关 gateway(三种加载方式) √
- 4、分布式 http feign √
- 5、熔断降级限流 Sentinel √
- 6、分布式文件 Minio、阿里OSS √
- 7、统一权限控制 JWT + Shiro √
- 8、服务监控 SpringBootAdmin√
- 9、链路跟踪 Skywalking [参考文档](https://help.jeecg.com/java/springcloud/super/skywarking.html)
- 10、消息中间件 RabbitMQ √
- 11、分布式任务 xxl-job √
- 12、分布式事务 Seata
- 13、轻量分布式日志 Loki+grafana套件
- 14、支持 docker-compose、k8s、jenkins
- 15、CAS 单点登录 √
- 16、路由限流 √
后台目录结构
-----------------------------------
```
项目结构
├─jeecg-boot-parent父POM 项目依赖、modules组织
│ ├─jeecg-boot-base-core共通模块 工具类、config、权限、查询过滤器、注解等
│ ├─jeecg-module-demo 示例代码
│ ├─jeecg-module-system System系统管理目录
│ │ ├─jeecg-system-biz System系统管理权限等功能
│ │ ├─jeecg-system-start System单体启动项目(8080
│ │ ├─jeecg-system-api System系统管理模块对外api
│ │ │ ├─jeecg-system-cloud-api System模块对外提供的微服务接口
│ │ │ ├─jeecg-system-local-api System模块对外提供的单体接口
│ ├─jeecg-server-cloud --微服务模块
├─jeecg-cloud-gateway --微服务网关模块(9999)
├─jeecg-cloud-nacos --Nacos服务模块(8848)
├─jeecg-system-cloud-start --System微服务启动项目(7001)
├─jeecg-demo-cloud-start --Demo微服务启动项目(7002)
├─jeecg-visual
├─jeecg-cloud-monitor --微服务监控模块 (9111)
├─jeecg-cloud-xxljob --微服务xxljob定时任务服务端 (9080)
├─jeecg-cloud-sentinel --sentinel服务端 (9000)
├─jeecg-cloud-test -- 微服务测试示例(各种例子)
├─jeecg-cloud-test-more -- 微服务测试示例feign、熔断降级、xxljob、分布式锁
├─jeecg-cloud-test-rabbitmq -- 微服务测试示例rabbitmq
├─jeecg-cloud-test-seata -- 微服务测试示例seata分布式事务
├─jeecg-cloud-test-shardingsphere -- 微服务测试示例(分库分表)
```
#### 微服务架构图
![微服务架构图](https://jeecgos.oss-cn-beijing.aliyuncs.com/files/jeecgboot_springcloud2022.png "在这里输入图片标题")

View File

@ -1,4 +1,4 @@
FROM mysql:8.0.19 FROM registry.cn-hangzhou.aliyuncs.com/jeecgdocker/mysql:8.0.19
MAINTAINER jeecgos@163.com MAINTAINER jeecgos@163.com

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,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

@ -3,6 +3,7 @@
> JeecgBoot属于平台级产品每次升级改动较大目前做不到平滑升级。 > JeecgBoot属于平台级产品每次升级改动较大目前做不到平滑升级。
### 增量升级方案 ### 增量升级方案
#### 1.代码合并 #### 1.代码合并
本地通过svn或git做好主干在分支上做业务开发jeecg每次版本发布可以手工覆盖主干的代码对比合并代码 本地通过svn或git做好主干在分支上做业务开发jeecg每次版本发布可以手工覆盖主干的代码对比合并代码
@ -11,5 +12,12 @@
- 其他库请手工执行SQL, 目录: `jeecg-module-system\jeecg-system-start\src\main\resources\flyway\sql\mysql` - 其他库请手工执行SQL, 目录: `jeecg-module-system\jeecg-system-start\src\main\resources\flyway\sql\mysql`
> 注意: 升级sql只提供mysql版本如果有权限升级, 还需要手工角色授权,退出重新登录才好使。 > 注意: 升级sql只提供mysql版本如果有权限升级, 还需要手工角色授权,退出重新登录才好使。
#### 3.兼容问题 #### 3.其他数据库脚本说明
原先官方默认提供oracle和SqlServer的脚本但是维护成本太高未提供脚本的数据库可以参考下面的文档自己转
https://my.oschina.net/jeecg/blog/4905722
注意定时任务的表qrtz_*,需要删掉用原始的脚本重新执行一下)
quartz-2.2.3-distribution.tar.gz放到百度网盘中大家自己下载执行所需数据库脚本
https://pan.baidu.com/s/1WrmZdUuAPg3iBwJ-LoHWyg?pwd=8mdz
#### 4.兼容问题
每次发版,会针对不兼容地方重点说明。 每次发版,会针对不兼容地方重点说明。

View File

@ -23,7 +23,7 @@ services:
- jeecg-boot - jeecg-boot
jeecg-boot-redis: jeecg-boot-redis:
image: redis:5.0 image: registry.cn-hangzhou.aliyuncs.com/jeecgdocker/redis:5.0
ports: ports:
- 6379:6379 - 6379:6379
restart: always restart: always

View File

@ -4,15 +4,11 @@
<parent> <parent>
<groupId>org.jeecgframework.boot</groupId> <groupId>org.jeecgframework.boot</groupId>
<artifactId>jeecg-boot-parent</artifactId> <artifactId>jeecg-boot-parent</artifactId>
<version>3.7.0</version> <version>3.7.2</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>jeecg-boot-base-core</artifactId> <artifactId>jeecg-boot-base-core</artifactId>
<properties>
<spring-boot.version>3.1.5</spring-boot.version>
</properties>
<repositories> <repositories>
<repository> <repository>
<id>aliyun</id> <id>aliyun</id>
@ -47,22 +43,12 @@
<!--jeecg-tools--> <!--jeecg-tools-->
<dependency> <dependency>
<groupId>org.jeecgframework.boot</groupId> <groupId>org.jeecgframework.boot</groupId>
<artifactId>jeecg-boot-common3</artifactId> <artifactId>jeecg-boot-common</artifactId>
</dependency> </dependency>
<!--集成springmvc框架并实现自动配置 --> <!--集成springmvc框架并实现自动配置 -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <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> </dependency>
<!-- websocket --> <!-- websocket -->
<dependency> <dependency>
@ -119,14 +105,14 @@
<!-- druid --> <!-- druid -->
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-3-starter</artifactId> <artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version> <version>${druid.version}</version>
</dependency> </dependency>
<!-- 动态数据源 --> <!-- 动态数据源 -->
<dependency> <dependency>
<groupId>com.baomidou</groupId> <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> <version>${dynamic-datasource-spring-boot-starter.version}</version>
</dependency> </dependency>
@ -163,7 +149,7 @@
<dependency> <dependency>
<groupId>org.jeecgframework</groupId> <groupId>org.jeecgframework</groupId>
<artifactId>kingbase8</artifactId> <artifactId>kingbase8</artifactId>
<version>${kingbase8.version}</version> <version>9.0.0</version>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<!--达梦数据库驱动 版本号1-3-26-2023.07.26-197096-20046-ENT --> <!--达梦数据库驱动 版本号1-3-26-2023.07.26-197096-20046-ENT -->
@ -178,7 +164,6 @@
<version>${dm8.version}</version> <version>${dm8.version}</version>
</dependency> </dependency>
<!-- Quartz定时任务 --> <!-- Quartz定时任务 -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
@ -192,25 +177,38 @@
<version>${java-jwt.version}</version> <version>${java-jwt.version}</version>
</dependency> </dependency>
<!--shiro-->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.apache.shiro</groupId>
<artifactId>spring-boot-starter-oauth2-authorization-server</artifactId> <artifactId>shiro-spring-boot-starter</artifactId>
<version>${shiro.version}</version>
</dependency> </dependency>
<!-- shiro-redis -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.crazycake</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId> <artifactId>shiro-redis</artifactId>
</dependency> <version>${shiro-redis.version}</version>
<!-- 添加spring security cas支持 --> <exclusions>
<dependency> <exclusion>
<groupId>org.springframework.security</groupId> <groupId>org.apache.shiro</groupId>
<artifactId>spring-security-cas</artifactId> <artifactId>shiro-core</artifactId>
</exclusion>
<exclusion>
<artifactId>checkstyle</artifactId>
<groupId>com.puppycrawl.tools</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
<!-- knife4j --> <!-- knife4j -->
<!-- <dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>-->
<dependency> <dependency>
<groupId>com.github.xiaoymin</groupId> <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> <version>${knife4j-spring-boot-starter.version}</version>
</dependency> </dependency>
@ -224,7 +222,7 @@
<!-- AutoPoi Excel工具类--> <!-- AutoPoi Excel工具类-->
<dependency> <dependency>
<groupId>org.jeecgframework.boot3</groupId> <groupId>org.jeecgframework</groupId>
<artifactId>autopoi-web</artifactId> <artifactId>autopoi-web</artifactId>
<version>${autopoi-web.version}</version> <version>${autopoi-web.version}</version>
<exclusions> <exclusions>
@ -267,16 +265,6 @@
<dependency> <dependency>
<groupId>com.xkcoding.justauth</groupId> <groupId>com.xkcoding.justauth</groupId>
<artifactId>justauth-spring-boot-starter</artifactId> <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>
<dependency> <dependency>
<groupId>com.squareup.okhttp3</groupId> <groupId>com.squareup.okhttp3</groupId>
@ -304,7 +292,7 @@
<!-- chatgpt --> <!-- chatgpt -->
<dependency> <dependency>
<groupId>org.jeecgframework.boot</groupId> <groupId>org.jeecgframework.boot</groupId>
<artifactId>jeecg-boot-starter3-chatgpt</artifactId> <artifactId>jeecg-boot-starter-chatgpt</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </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; package org.jeecg.common.api;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.system.vo.*; import org.jeecg.common.system.vo.*;
import java.util.List; import java.util.List;
@ -65,13 +64,6 @@ public interface CommonAPI {
*/ */
public String getUserIdByName(String username); public String getUserIdByName(String username);
/**
* 5根据用户手机号查询用户信息
* @param username
* @return
*/
public LoginUser getUserByPhone(String phone);
/** /**
* 6字典表的 翻译 * 6字典表的 翻译
@ -152,31 +144,4 @@ public interface CommonAPI {
List<DictModel> translateDictFromTableByKeys(String table, String text, String code, String keys, String dataSource); List<DictModel> translateDictFromTableByKeys(String table, String text, String code, String keys, String dataSource);
//update-end---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------ //update-end---author:chenrui ---date:20231221 for[issues/#5643]解决分布式下表字典跨库无法查询问题------------
/**
* 登录加载系统字典
* @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);
} }

View File

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

View File

@ -84,6 +84,12 @@ public class MessageDTO implements Serializable {
* 邮件抄送地址 * 邮件抄送地址
*/ */
protected Set<String> ccEmailList; protected Set<String> ccEmailList;
/**
* 是否为定时任务推送email
*/
private Boolean isTimeJob = false;
//---【邮件相关参数】------------------------------------------------------------- //---【邮件相关参数】-------------------------------------------------------------
public MessageDTO(){ public MessageDTO(){

View File

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

View File

@ -1,6 +1,5 @@
package org.jeecg.common.aspect; package org.jeecg.common.aspect;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter; import com.alibaba.fastjson.serializer.PropertyFilter;
import org.apache.shiro.SecurityUtils; import org.apache.shiro.SecurityUtils;
@ -16,21 +15,19 @@ import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ModuleType; import org.jeecg.common.constant.enums.ModuleType;
import org.jeecg.common.constant.enums.OperateTypeEnum; import org.jeecg.common.constant.enums.OperateTypeEnum;
import org.jeecg.config.security.utils.SecureUtil;
import org.jeecg.modules.base.service.BaseCommonService; import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.common.system.vo.LoginUser; import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.IpUtils; import org.jeecg.common.util.IpUtils;
import org.jeecg.common.util.SpringContextUtils; import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils; import org.jeecg.common.util.oConvertUtils;
import org.springframework.core.StandardReflectionParameterNameDiscoverer; import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import jakarta.annotation.Resource; import javax.annotation.Resource;
import jakarta.servlet.ServletRequest; import javax.servlet.ServletRequest;
import jakarta.servlet.ServletResponse; import javax.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Date; import java.util.Date;
@ -103,7 +100,7 @@ public class AutoLogAspect {
//设置IP地址 //设置IP地址
dto.setIp(IpUtils.getIpAddr(request)); dto.setIp(IpUtils.getIpAddr(request));
//获取登录用户信息 //获取登录用户信息
LoginUser sysUser = SecureUtil.currentUser(); LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
if(sysUser!=null){ if(sysUser!=null){
dto.setUserid(sysUser.getUsername()); dto.setUserid(sysUser.getUsername());
dto.setUsername(sysUser.getRealname()); dto.setUsername(sysUser.getRealname());
@ -175,7 +172,7 @@ public class AutoLogAspect {
// 请求的方法参数值 // 请求的方法参数值
Object[] args = joinPoint.getArgs(); Object[] args = joinPoint.getArgs();
// 请求的方法参数名称 // 请求的方法参数名称
StandardReflectionParameterNameDiscoverer u=new StandardReflectionParameterNameDiscoverer(); LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
String[] paramNames = u.getParameterNames(method); String[] paramNames = u.getParameterNames(method);
if (args != null && paramNames != null) { if (args != null && paramNames != null) {
for (int i = 0; i < args.length; i++) { for (int i = 0; i < args.length; i++) {

View File

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

View File

@ -90,7 +90,7 @@ public interface CommonConstant {
/** 登录用户Shiro权限缓存KEY前缀 */ /** 登录用户Shiro权限缓存KEY前缀 */
public static String PREFIX_USER_SHIRO_CACHE = "shiro:cache:org.jeecg.config.shiro.ShiroRealm.authorizationCache:"; public static String PREFIX_USER_SHIRO_CACHE = "shiro:cache:org.jeecg.config.shiro.ShiroRealm.authorizationCache:";
/** 登录用户Token令牌缓存KEY前缀 */ /** 登录用户Token令牌缓存KEY前缀 */
String PREFIX_USER_TOKEN = "token::jeecg-client::"; String PREFIX_USER_TOKEN = "prefix_user_token:";
// /** Token缓存时间3600秒即一小时 */ // /** Token缓存时间3600秒即一小时 */
// int TOKEN_EXPIRE_TIME = 3600; // int TOKEN_EXPIRE_TIME = 3600;
@ -144,7 +144,9 @@ public interface CommonConstant {
*/ */
String STATUS_0 = "0"; String STATUS_0 = "0";
String STATUS_1 = "1"; String STATUS_1 = "1";
Integer STATUS_0_INT = 0;
Integer STATUS_1_INT = 1;
/** /**
* 同步工作流引擎1同步0不同步 * 同步工作流引擎1同步0不同步
*/ */
@ -475,6 +477,11 @@ public interface CommonConstant {
*/ */
String FILE_EDITABLE = "editable"; String FILE_EDITABLE = "editable";
/**
* 文件 只读
*/
String FILE_READONLY = "readonly";
/** /**
* 登录失败用于记录失败次数的key * 登录失败用于记录失败次数的key
*/ */
@ -597,6 +604,11 @@ public interface CommonConstant {
*/ */
String CHANGE_PHONE_REDIS_KEY_PRE = "sys:cache:phone:change_phone_msg:"; String CHANGE_PHONE_REDIS_KEY_PRE = "sys:cache:phone:change_phone_msg:";
/**
* 手机号短信验证码redis-key的前缀
*/
String LOG_OFF_PHONE_REDIS_KEY_PRE = "sys:cache:phone:qqy_log_off_user_msg:";
/** /**
* 缓存用户最后一次收到消息通知的时间 KEY * 缓存用户最后一次收到消息通知的时间 KEY
*/ */

View File

@ -1,6 +1,7 @@
package org.jeecg.common.constant; package org.jeecg.common.constant;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.oConvertUtils; import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
@ -22,26 +23,30 @@ public class ProvinceCityArea {
List<Area> areaList; List<Area> areaList;
public String getText(String code){ public String getText(String code){
this.initAreaList(); if(StringUtils.isNotBlank(code)){
if(this.areaList!=null || this.areaList.size()>0){ this.initAreaList();
List<String> ls = new ArrayList<String>(); if(this.areaList!=null || this.areaList.size()>0){
getAreaByCode(code,ls); List<String> ls = new ArrayList<String>();
return String.join("/",ls); getAreaByCode(code,ls);
return String.join("/",ls);
}
} }
return ""; return "";
} }
public String getCode(String text){ public String getCode(String text){
this.initAreaList(); if(StringUtils.isNotBlank(text)){
if(areaList!=null && areaList.size()>0){ this.initAreaList();
for(int i=areaList.size()-1;i>=0;i--){ if(areaList!=null && areaList.size()>0){
//update-begin-author:taoyan date:2022-5-24 for:VUEN-1088 online 导入 省市区导入后 导入数据错乱 北京市/市辖区/西城区-->山西省/晋城市/城区 for(int i=areaList.size()-1;i>=0;i--){
String areaText = areaList.get(i).getText(); //update-begin-author:taoyan date:2022-5-24 for:VUEN-1088 online 导入 省市区导入后 导入数据错乱 北京市/市辖区/西城区-->山西省/晋城市/城区
String cityText = areaList.get(i).getAheadText(); String areaText = areaList.get(i).getText();
if(text.indexOf(areaText)>=0 && (cityText!=null && text.indexOf(cityText)>=0)){ String cityText = areaList.get(i).getAheadText();
return areaList.get(i).getId(); if(text.indexOf(areaText)>=0 && (cityText!=null && text.indexOf(cityText)>=0)){
return areaList.get(i).getId();
}
//update-end-author:taoyan date:2022-5-24 for:VUEN-1088 online 导入 省市区导入后 导入数据错乱 北京市/市辖区/西城区-->山西省/晋城市/城区
} }
//update-end-author:taoyan date:2022-5-24 for:VUEN-1088 online 导入 省市区导入后 导入数据错乱 北京市/市辖区/西城区-->山西省/晋城市/城区
} }
} }
return null; return null;

View File

@ -15,15 +15,7 @@ public enum DySmsEnum {
/**修改密码短信模板编码*/ /**修改密码短信模板编码*/
CHANGE_PASSWORD_TEMPLATE_CODE("SMS_465391221","敲敲云","code"), CHANGE_PASSWORD_TEMPLATE_CODE("SMS_465391221","敲敲云","code"),
/**注册账号短信模板编码*/ /**注册账号短信模板编码*/
REGISTER_TEMPLATE_CODE("SMS_175430166","敲敲云","code"), REGISTER_TEMPLATE_CODE("SMS_175430166","敲敲云","code");
/**会议通知*/
MEET_NOTICE_TEMPLATE_CODE("SMS_201480469","JEECG","username,title,minute,time"),
/**我的计划通知*/
PLAN_NOTICE_TEMPLATE_CODE("SMS_201470515","JEECG","username,title,time"),
/**支付成功短信通知*/
PAY_SUCCESS_NOTICE_CODE("SMS_461735163","敲敲云","realname,money,endTime"),
/**会员到期通知提醒*/
VIP_EXPIRE_NOTICE_CODE("SMS_461885023","敲敲云","realname,endTime");
/** /**
* 短信模板编码 * 短信模板编码

View File

@ -1,11 +1,11 @@
package org.jeecg.common.exception; package org.jeecg.common.exception;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.shiro.SecurityUtils; 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.dto.LogDTO;
import org.jeecg.common.api.vo.Result; import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.CommonConstant;
@ -22,8 +22,6 @@ import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException; import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.connection.PoolException; import org.springframework.data.redis.connection.PoolException;
import org.springframework.http.HttpStatus; 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.util.CollectionUtils;
import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
@ -32,6 +30,8 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException; import org.springframework.web.servlet.NoHandlerFoundException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map; import java.util.Map;
/** /**
@ -43,27 +43,9 @@ import java.util.Map;
@RestControllerAdvice @RestControllerAdvice
@Slf4j @Slf4j
public class JeecgBootExceptionHandler { public class JeecgBootExceptionHandler {
@Resource @Resource
BaseCommonService baseCommonService; BaseCommonService baseCommonService;
/**
* 验证码错误异常
*/
@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());
}
/** /**
* 处理自定义异常 * 处理自定义异常
@ -119,10 +101,10 @@ public class JeecgBootExceptionHandler {
return Result.error("数据库中已存在该记录"); return Result.error("数据库中已存在该记录");
} }
@ExceptionHandler(AccessDeniedException.class) @ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
public Result<?> handleAuthorizationException(AccessDeniedException e){ public Result<?> handleAuthorizationException(AuthorizationException e){
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return Result.noauth("没有权限,请联系管理员授权,后刷新缓存!"); return Result.noauth("没有权限,请联系管理员分配权限!");
} }
@ExceptionHandler(Exception.class) @ExceptionHandler(Exception.class)

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; 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.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result; import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator; import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser; import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils; import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.JeecgBaseConfig; import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.config.security.utils.SecureUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil; import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants; import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams; 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.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView; import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired; 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.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import jakarta.annotation.Resource; import javax.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.*; 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) { protected ModelAndView exportXls(HttpServletRequest request, T object, Class<T> clazz, String title) {
// Step.1 组装查询条件 // Step.1 组装查询条件
QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap()); QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
LoginUser sysUser = SecureUtil.currentUser(); LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
// 过滤选中数据 // 过滤选中数据
String selections = request.getParameter("selections"); 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) { protected ModelAndView exportXlsSheet(HttpServletRequest request, T object, Class<T> clazz, String title,String exportFields,Integer pageNum) {
// Step.1 组装查询条件 // Step.1 组装查询条件
QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap()); QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
LoginUser sysUser = SecureUtil.currentUser(); LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
// Step.2 计算分页sheet数据 // Step.2 计算分页sheet数据
double total = service.count(); double total = service.count();
int count = (int)Math.ceil(total/pageNum); 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.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import io.swagger.v3.oas.annotations.media.Schema;
/** /**
* @Description: Entity基类 * @Description: Entity基类
@ -30,20 +30,20 @@ public class JeecgEntity implements Serializable {
* ID * ID
*/ */
@TableId(type = IdType.ASSIGN_ID) @TableId(type = IdType.ASSIGN_ID)
@Schema(description = "ID") @ApiModelProperty(value = "ID")
private java.lang.String id; private java.lang.String id;
/** /**
* 创建人 * 创建人
*/ */
@Schema(description = "创建人") @ApiModelProperty(value = "创建人")
@Excel(name = "创建人", width = 15) @Excel(name = "创建人", width = 15)
private java.lang.String createBy; private java.lang.String createBy;
/** /**
* 创建时间 * 创建时间
*/ */
@Schema(description = "创建时间") @ApiModelProperty(value = "创建时间")
@Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss") @Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "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") @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) @Excel(name = "更新人", width = 15)
private java.lang.String updateBy; private java.lang.String updateBy;
/** /**
* 更新时间 * 更新时间
*/ */
@Schema(description = "更新时间") @ApiModelProperty(value = "更新时间")
@Excel(name = "更新时间", width = 20, format = "yyyy-MM-dd HH:mm:ss") @Excel(name = "更新时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "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") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")

View File

@ -746,7 +746,11 @@ public class QueryGenerator {
private static boolean judgedIsUselessField(String name) { private static boolean judgedIsUselessField(String name) {
return "class".equals(name) || "ids".equals(name) return "class".equals(name) || "ids".equals(name)
|| "page".equals(name) || "rows".equals(name) || "page".equals(name) || "rows".equals(name)
|| "sort".equals(name) || "order".equals(name); //// update-begin--author:sunjianlei date:20240808 for【TV360X-2009】取消过滤 sort、order 字段,防止前端排序报错 ------
//// https://github.com/jeecgboot/JeecgBoot/issues/6937
// || "sort".equals(name) || "order".equals(name)
//// update-end----author:sunjianlei date:20240808 for【TV360X-2009】取消过滤 sort、order 字段,防止前端排序报错 ------
;
} }
@ -801,7 +805,9 @@ public class QueryGenerator {
addEasyQuery(queryWrapper, name, rule, DateUtils.str2Date(dateStr,DateUtils.datetimeFormat.get())); addEasyQuery(queryWrapper, name, rule, DateUtils.str2Date(dateStr,DateUtils.datetimeFormat.get()));
} }
}else { }else {
addEasyQuery(queryWrapper, name, rule, NumberUtils.parseNumber(dataRule.getRuleValue(), propertyType)); //update-begin---author:chenrui ---date:20241125 for[issues/7481]多租户模式下 数据权限使用变量:#{tenant_id} 报错------------
addEasyQuery(queryWrapper, name, rule, NumberUtils.parseNumber(converRuleValue(dataRule.getRuleValue()), propertyType));
//update-end---author:chenrui ---date:20241125 for[issues/7481]多租户模式下 数据权限使用变量:#{tenant_id} 报错------------
} }
} }
} }
@ -834,6 +840,9 @@ public class QueryGenerator {
public static String getSqlRuleValue(String sqlRule){ public static String getSqlRuleValue(String sqlRule){
try { try {
Set<String> varParams = getSqlRuleParams(sqlRule); Set<String> varParams = getSqlRuleParams(sqlRule);
if (varParams == null || varParams.isEmpty()) {
return sqlRule;
}
for(String var:varParams){ for(String var:varParams){
String tempValue = converRuleValue(var); String tempValue = converRuleValue(var);
sqlRule = sqlRule.replace("#{"+var+"}",tempValue); sqlRule = sqlRule.replace("#{"+var+"}",tempValue);

View File

@ -54,8 +54,10 @@ public enum QueryRuleEnum {
NOT_EMPTY("NOT_EMPTY","not_empty","值不为空"), NOT_EMPTY("NOT_EMPTY","not_empty","值不为空"),
/**查询规则 不包含*/ /**查询规则 不包含*/
NOT_IN("NOT_IN","not_in","不包含"), NOT_IN("NOT_IN","not_in","不包含"),
/**查询规则 多词匹配*/ /**查询规则 多词精确匹配*/
ELE_MATCH("ELE_MATCH","elemMatch","多词匹配"), ELE_MATCH("ELE_MATCH","elemMatch","多词匹配"),
/**查询规则 多词精确不匹配*/
ELE_NOT_MATCH("ELE_NOT_MATCH","elemNotMatch","多词精确不匹配"),
/**查询规则 范围查询*/ /**查询规则 范围查询*/
RANGE("RANGE","range","范围查询"), RANGE("RANGE","range","范围查询"),
/**查询规则 不在范围内查询*/ /**查询规则 不在范围内查询*/

View File

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

View File

@ -1,7 +1,5 @@
package org.jeecg.common.system.util; 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.JWT;
import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.algorithms.Algorithm;
@ -12,17 +10,14 @@ import com.google.common.base.Joiner;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.*; import java.util.Date;
import java.util.stream.Collectors; import javax.servlet.ServletResponse;
import java.util.stream.Stream; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jakarta.servlet.ServletResponse; import javax.servlet.http.HttpSession;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j; 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.api.vo.Result;
import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.DataBaseConstant; 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.DateUtils;
import org.jeecg.common.util.SpringContextUtils; import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils; 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 * @Author Scott
@ -63,8 +42,6 @@ public class JwtUtil {
public static final long EXPIRE_TIME = (7 * 12) * 60 * 60 * 1000; public static final long EXPIRE_TIME = (7 * 12) * 60 * 60 * 1000;
static final String WELL_NUMBER = SymbolConstant.WELL_NUMBER + SymbolConstant.LEFT_CURLY_BRACKET; static final String WELL_NUMBER = SymbolConstant.WELL_NUMBER + SymbolConstant.LEFT_CURLY_BRACKET;
public static final String DEFAULT_CLIENT = "jeecg-client";
/** /**
* *
* @param response * @param response
@ -86,7 +63,7 @@ public class JwtUtil {
os.flush(); os.flush();
os.close(); os.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); log.error(e.getMessage(), e);
} }
} }
@ -100,11 +77,13 @@ public class JwtUtil {
public static boolean verify(String token, String username, String secret) { public static boolean verify(String token, String username, String secret) {
try { try {
// 根据密码生成JWT效验器 // 根据密码生成JWT效验器
JwtDecoder jwtDecoder = SpringContextUtils.getBean(JwtDecoder.class); Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
// 效验TOKEN // 效验TOKEN
jwtDecoder.decode(token); DecodedJWT jwt = verifier.verify(token);
return true; return true;
} catch (Exception exception) { } catch (Exception e) {
log.error(e.getMessage(), e);
return false; return false;
} }
} }
@ -117,33 +96,25 @@ public class JwtUtil {
public static String getUsername(String token) { public static String getUsername(String token) {
try { try {
DecodedJWT jwt = JWT.decode(token); DecodedJWT jwt = JWT.decode(token);
LoginUser loginUser = JSONObject.parseObject(jwt.getClaim("sub").asString(), LoginUser.class); return jwt.getClaim("username").asString();
return loginUser.getUsername();
} catch (JWTDecodeException e) { } catch (JWTDecodeException e) {
log.warn(e.getMessage(), e);
return null; return null;
} }
} }
/** /**
* 生成token * 生成签名,5min后过期
* *
* @param username 用户名 * @param username 用户名
* @param secret 用户的密码 * @param secret 用户的密码
* @return 加密的token * @return 加密的token
*/ */
public static String sign(String username, String secret) { public static String sign(String username, String secret) {
Map<String, Object> additionalParameter = new HashMap<>(); Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
additionalParameter.put("username", username); Algorithm algorithm = Algorithm.HMAC256(secret);
// 附带username信息
RegisteredClientRepository registeredClientRepository = SpringContextUtils.getBean(RegisteredClientRepository.class); return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm);
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();
} }
@ -208,7 +179,7 @@ public class JwtUtil {
//2.通过shiro获取登录用户信息 //2.通过shiro获取登录用户信息
LoginUser sysUser = null; LoginUser sysUser = null;
try { try {
sysUser = SecureUtil.currentUser(); sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
} catch (Exception e) { } catch (Exception e) {
log.warn("SecurityUtils.getSubject() 获取用户信息异常:" + e.getMessage()); log.warn("SecurityUtils.getSubject() 获取用户信息异常:" + e.getMessage());
} }

View File

@ -1,18 +1,13 @@
package org.jeecg.common.system.vo; package org.jeecg.common.system.vo;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import org.jeecg.common.desensitization.annotation.SensitiveField; import org.jeecg.common.desensitization.annotation.SensitiveField;
import org.springframework.format.annotation.DateTimeFormat; 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.Date;
import java.util.Set;
/** /**
* <p> * <p>
@ -25,10 +20,8 @@ import java.util.Set;
@Data @Data
@EqualsAndHashCode(callSuper = false) @EqualsAndHashCode(callSuper = false)
@Accessors(chain = true) @Accessors(chain = true)
public class LoginUser implements Serializable { public class LoginUser {
private static final long serialVersionUID = -7143159031677245866L;
/** /**
* 登录人id * 登录人id
*/ */
@ -145,29 +138,4 @@ public class LoginUser implements Serializable {
/**设备id uniapp推送用*/ /**设备id uniapp推送用*/
private String clientId; 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

@ -5,7 +5,7 @@ import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; 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.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;

View File

@ -1,5 +1,6 @@
package org.jeecg.common.util; package org.jeecg.common.util;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient; import com.aliyuncs.IAcsClient;
@ -8,11 +9,15 @@ import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.profile.IClientProfile;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.enums.DySmsEnum; import org.jeecg.common.constant.enums.DySmsEnum;
import org.jeecg.config.JeecgSmsTemplateConfig;
import org.jeecg.config.StaticConfig; import org.jeecg.config.StaticConfig;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Map;
/** /**
* Created on 17/6/7. * Created on 17/6/7.
* 短信API产品的DEMO程序,工程中包含了一个SmsDemo类直接通过 * 短信API产品的DEMO程序,工程中包含了一个SmsDemo类直接通过
@ -75,15 +80,33 @@ public class DySmsHelper {
//验证json参数 //验证json参数
validateParam(templateParamJson,dySmsEnum); validateParam(templateParamJson,dySmsEnum);
//update-begin---author:wangshuai---date:2024-11-05---for:【QQYUN-9422】短信模板管理阿里云---
String templateCode = dySmsEnum.getTemplateCode();
JeecgSmsTemplateConfig baseConfig = SpringContextUtils.getBean(JeecgSmsTemplateConfig.class);
if(baseConfig != null && CollectionUtil.isNotEmpty(baseConfig.getTemplateCode())){
Map<String, String> smsTemplate = baseConfig.getTemplateCode();
if(smsTemplate.containsKey(templateCode) && StringUtils.isNotEmpty(smsTemplate.get(templateCode))){
templateCode = smsTemplate.get(templateCode);
logger.info("yml中读取短信code{}",templateCode);
}
}
//签名名称
String signName = dySmsEnum.getSignName();
if(baseConfig != null && StringUtils.isNotEmpty(baseConfig.getSignature())){
logger.info("yml中读取签名名称{}",baseConfig.getSignature());
signName = baseConfig.getSignature();
}
//update-end---author:wangshuai---date:2024-11-05---for:【QQYUN-9422】短信模板管理阿里云---
//组装请求对象-具体描述见控制台-文档部分内容 //组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest(); SendSmsRequest request = new SendSmsRequest();
//必填:待发送手机号 //必填:待发送手机号
request.setPhoneNumbers(phone); request.setPhoneNumbers(phone);
//必填:短信签名-可在短信控制台中找到 //必填:短信签名-可在短信控制台中找到
request.setSignName(dySmsEnum.getSignName()); request.setSignName(signName);
//必填:短信模板-可在短信控制台中找到 //必填:短信模板-可在短信控制台中找到
request.setTemplateCode(dySmsEnum.getTemplateCode()); request.setTemplateCode(templateCode);
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
request.setTemplateParam(templateParamJson.toJSONString()); request.setTemplateParam(templateParamJson.toJSONString());

View File

@ -0,0 +1,206 @@
package org.jeecg.common.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.jeecg.common.exception.JeecgBootException;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @program: file
* @description: 文件下载
* @author: chenrui
* @date: 2019-05-24 16:34
**/
@Slf4j
public class FileDownloadUtils {
/**
* 单文件下载
*
* @param response
* @param storePath 下载文件储存地址
* @param fileName 文件名称
* @author: chenrui
* @date: 2019/5/24 17:10
*/
public static void downloadFile(HttpServletResponse response, String storePath, String fileName) {
response.setCharacterEncoding("UTF-8");
File file = new File(storePath);
if (!file.exists()) {
throw new NullPointerException("Specified file not found");
}
if (fileName == null || fileName.isEmpty()) {
throw new NullPointerException("The file name can not null");
}
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
try {
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
// 实现文件下载
byte[] buffer = new byte[1024];
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);) {
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
/**
* 多文件下载
*
* @param filesPath 下载文件集合
* @param zipFileName 多文件合称名
* @author: chenrui
* @date: 2019/5/24 17:48
*/
public static void downloadFileMulti(HttpServletResponse response, List<String> filesPath, String zipFileName) throws IOException {
//设置压缩包的名字
String downloadName = zipFileName + ".zip";
response.setCharacterEncoding("UTF-8");
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadName, "UTF-8"));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
log.info("开始压缩文件:" + filesPath);
//设置压缩流直接写入response实现边压缩边下载
try (ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
DataOutputStream os = new DataOutputStream(zipOut);) {
//设置压缩方法
zipOut.setMethod(ZipOutputStream.DEFLATED);
for (String filePath : filesPath) {
//循环将文件写入压缩流
File file = new File(filePath);
if (file.exists()) {
//添加ZipEntry并ZipEntry中写入文件流也就是将文件压入zip文件的目录下
String fileName = file.getName();
zipOut.putNextEntry(new ZipEntry(fileName));
//格式输出流文件
InputStream is = Files.newInputStream(file.toPath());
byte[] b = new byte[1024];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
zipOut.closeEntry();
}
}
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new JeecgBootException(e);
}
}
/**
* 下载网络资源到磁盘
*
* @param fileUrl
* @param storePath
* @author chenrui
* @date 2024/1/19 10:09
*/
public static String download2DiskFromNet(String fileUrl, String storePath) {
try {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
// 防止屏蔽程序
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// 确保目录存在
File file = ensureDestFileDir(storePath);
try (InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream(file);) {
int byteread;
byte[] buffer = new byte[1204];
while ((byteread = inStream.read(buffer)) != -1) {
fs.write(buffer, 0, byteread);
}
return storePath;
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new JeecgBootException(e);
}
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new JeecgBootException(e);
}
}
/**
* 获取不重名的文件
*
* @param file
* @return
* @author chenrui
* @date 2017年5月24日下午6:29:13
* @version v0.0.1
*/
public static File getUniqueFile(final File file) {
if (!file.exists()) {
return file;
}
File tmpFile = new File(file.getAbsolutePath());
File parentDir = tmpFile.getParentFile();
int count = 1;
String extension = FilenameUtils.getExtension(tmpFile.getName());
String baseName = FilenameUtils.getBaseName(tmpFile.getName());
do {
tmpFile = new File(parentDir, baseName + "(" + count++ + ")." + extension);
} while (tmpFile.exists());
return tmpFile;
}
/**
* 确保输出文件目录
*
* @param destFilePath
* @return
* @author: chenrui
* @date: 2019-05-21 16:49
*/
private static File ensureDestFileDir(String destFilePath) {
File destFile = new File(destFilePath);
FileDownloadUtils.checkDirAndCreate(destFile.getParentFile());
return destFile;
}
/**
* 验证文件夹存在且创建目录
*
* @param dir
* @author chenrui
* @date 2017年5月24日下午6:29:24
* @version v0.0.1
*/
public static void checkDirAndCreate(File dir) {
if (!dir.exists()) {
dir.mkdirs();
}
}
}

View File

@ -6,7 +6,11 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.handler.IFillRuleHandler; import org.jeecg.common.handler.IFillRuleHandler;
import org.jeecg.common.system.query.QueryGenerator;
import javax.servlet.http.HttpServletRequest;
/** /**
@ -42,6 +46,30 @@ public class FillRuleUtil {
if (params == null) { if (params == null) {
params = new JSONObject(); params = new JSONObject();
} }
HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
// 解析 params 中的变量
// 优先级queryString > 系统变量 > 默认值
for (String key : params.keySet()) {
// 1. 判断 queryString 中是否有该参数,如果有就优先取值
//noinspection ConstantValue
if (request != null) {
String parameter = request.getParameter(key);
if (oConvertUtils.isNotEmpty(parameter)) {
params.put(key, parameter);
continue;
}
}
String value = params.getString(key);
// 2. 用于替换 系统变量的值 #{sys_user_code}
if (value != null && value.contains(SymbolConstant.SYS_VAR_PREFIX)) {
value = QueryGenerator.getSqlRuleValue(value);
params.put(key, value);
}
}
if (formData == null) { if (formData == null) {
formData = new JSONObject(); formData = new JSONObject();
} }

View File

@ -1,7 +1,9 @@
package org.jeecg.common.util; package org.jeecg.common.util;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.pegdown.PegDownProcessor; import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.springframework.web.util.HtmlUtils; import org.springframework.web.util.HtmlUtils;
/** /**
@ -36,8 +38,14 @@ public class HTMLUtils {
* @return * @return
*/ */
public static String parseMarkdown(String markdownContent) { public static String parseMarkdown(String markdownContent) {
PegDownProcessor pdp = new PegDownProcessor(); //update-begin---author:wangshuai---date:2024-06-26---for:【TV360X-1344】JDK17 邮箱发送失败,需要换写法---
return pdp.markdownToHtml(markdownContent); /*PegDownProcessor pdp = new PegDownProcessor();
return pdp.markdownToHtml(markdownContent);*/
Parser parser = Parser.builder().build();
Node document = parser.parse(markdownContent);
HtmlRenderer renderer = HtmlRenderer.builder().build();
return renderer.render(document);
//update-end---author:wangshuai---date:2024-06-26---for:【TV360X-1344】JDK17 邮箱发送失败,需要换写法---
} }
} }

View File

@ -1,6 +1,6 @@
package org.jeecg.common.util; package org.jeecg.common.util;
import jakarta.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.CommonConstant;

View File

@ -57,8 +57,8 @@ public class RestUtil {
static { static {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(3000); requestFactory.setConnectTimeout(30000);
requestFactory.setReadTimeout(3000); requestFactory.setReadTimeout(30000);
RT = new RestTemplate(requestFactory); RT = new RestTemplate(requestFactory);
// 解决乱码问题 // 解决乱码问题
RT.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); RT.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

View File

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

View File

@ -11,13 +11,7 @@ import org.jeecg.common.exception.JeecgBoot401Exception;
import org.jeecg.common.system.util.JwtUtil; import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser; import org.jeecg.common.system.vo.LoginUser;
import jakarta.servlet.http.HttpServletRequest; import javax.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;
/** /**
* @Author scott * @Author scott
@ -112,8 +106,8 @@ public class TokenUtils {
} }
// 查询用户信息 // 查询用户信息
//LoginUser user = TokenUtils.getLoginUser(username, commonApi, redisUtil); LoginUser user = TokenUtils.getLoginUser(username, commonApi, redisUtil);
LoginUser user = commonApi.getUserByName(username); //LoginUser user = commonApi.getUserByName(username);
if (user == null) { if (user == null) {
throw new JeecgBoot401Exception("用户不存在!"); throw new JeecgBoot401Exception("用户不存在!");
} }
@ -122,7 +116,7 @@ public class TokenUtils {
throw new JeecgBoot401Exception("账号已被锁定,请联系管理员!"); throw new JeecgBoot401Exception("账号已被锁定,请联系管理员!");
} }
// 校验token是否超时失效 & 或者账号密码是否错误 // 校验token是否超时失效 & 或者账号密码是否错误
if (!jwtTokenRefresh(token, username, user.getPassword())) { if (!jwtTokenRefresh(token, username, user.getPassword(), redisUtil)) {
throw new JeecgBoot401Exception(CommonConstant.TOKEN_IS_INVALID_MSG); throw new JeecgBoot401Exception(CommonConstant.TOKEN_IS_INVALID_MSG);
} }
return true; return true;
@ -151,15 +145,6 @@ public class TokenUtils {
return false; 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;
}
/** /**
* 获取登录用户 * 获取登录用户
* *
@ -173,11 +158,10 @@ public class TokenUtils {
//【重要】此处通过redis原生获取缓存用户是为了解决微服务下system服务挂了其他服务互调不通问题--- //【重要】此处通过redis原生获取缓存用户是为了解决微服务下system服务挂了其他服务互调不通问题---
if (redisUtil.hasKey(loginUserKey)) { if (redisUtil.hasKey(loginUserKey)) {
try { try {
Object obj = redisUtil.get(loginUserKey); loginUser = (LoginUser) redisUtil.get(loginUserKey);
loginUser = (LoginUser) obj;
//解密用户 //解密用户
SensitiveInfoUtil.handlerObject(loginUser, false); SensitiveInfoUtil.handlerObject(loginUser, false);
} catch (Exception e) { } catch (IllegalAccessException e) {
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {

View File

@ -84,6 +84,10 @@ public class DynamicDBUtil {
} else { } else {
DruidDataSource dataSource = getJdbcDataSource(dbSource); DruidDataSource dataSource = getJdbcDataSource(dbSource);
if(dataSource!=null && dataSource.isEnable()){ if(dataSource!=null && dataSource.isEnable()){
// 【TV360X-2060】设置超时时间 6秒
dataSource.setMaxWait(6000);
DataSourceCachePool.putCacheBasicDataSource(dbKey, dataSource); DataSourceCachePool.putCacheBasicDataSource(dbKey, dataSource);
}else{ }else{
throw new JeecgBootException("动态数据源连接失败dbKey"+dbKey); throw new JeecgBootException("动态数据源连接失败dbKey"+dbKey);
@ -106,9 +110,10 @@ public class DynamicDBUtil {
dataSource.getConnection().commit(); dataSource.getConnection().commit();
dataSource.getConnection().close(); dataSource.getConnection().close();
dataSource.close(); dataSource.close();
DataSourceCachePool.removeCache(dbKey);
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.warn(e.getMessage(), e);
} }
} }

View File

@ -1,9 +1,10 @@
package org.jeecg.common.util.encryption; package org.jeecg.common.util.encryption;
import org.apache.shiro.codec.Base64;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
/** /**
* @Description: AES 加密 * @Description: AES 加密
@ -48,7 +49,7 @@ public class AesEncryptUtil {
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext); byte[] encrypted = cipher.doFinal(plaintext);
return Base64.getEncoder().encodeToString(encrypted); return Base64.encodeToString(encrypted);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -66,7 +67,7 @@ public class AesEncryptUtil {
*/ */
public static String desEncrypt(String data, String key, String iv) throws Exception { 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、解密报错 ---解码失败应该把异常抛出去,在外面处理 //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"); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");

View File

@ -9,7 +9,7 @@ import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.SymbolConstant; import org.jeecg.common.constant.SymbolConstant;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import jakarta.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
@ -463,7 +463,7 @@ public class oConvertUtils {
return false; return false;
} }
String[] childs = (String[]) childArray.toArray(); String[] childs = childArray.toArray(new String[]{});
for (String v : childs) { for (String v : childs) {
if (!isIn(v, all)) { if (!isIn(v, all)) {
return false; return false;

View File

@ -73,6 +73,12 @@ public class JSqlParserUtils {
* @return * @return
*/ */
private static SelectSqlInfo parseBySelectBody(SelectBody selectBody) { private static SelectSqlInfo parseBySelectBody(SelectBody selectBody) {
// 判断是否使用了union等操作
if (selectBody instanceof SetOperationList) {
// 如果使用了union等操作则只解析第一个查询
List<SelectBody> selectBodyList = ((SetOperationList) selectBody).getSelects();
return JSqlParserUtils.parseBySelectBody(selectBodyList.get(0));
}
// 简单的select查询 // 简单的select查询
if (selectBody instanceof PlainSelect) { if (selectBody instanceof PlainSelect) {
SelectSqlInfo sqlInfo = new SelectSqlInfo(selectBody); SelectSqlInfo sqlInfo = new SelectSqlInfo(selectBody);

View File

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

View File

@ -2,9 +2,7 @@ package org.jeecg.config;
import java.io.IOException; import java.io.IOException;
import com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceAutoConfigure; import javax.servlet.*;
import com.alibaba.druid.spring.boot3.autoconfigure.properties.DruidStatProperties;
import jakarta.servlet.*;
import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 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.Bean;
import org.springframework.context.annotation.Configuration; 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; import com.alibaba.druid.util.Utils;
/** /**

View File

@ -12,7 +12,6 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* @author eightmonth@qq.com
* 启动程序修改DruidWallConfig配置 * 启动程序修改DruidWallConfig配置
* 允许SELECT语句的WHERE子句是一个永真条件 * 允许SELECT语句的WHERE子句是一个永真条件
* @author eightmonth * @author eightmonth

View File

@ -32,6 +32,10 @@ public class JeecgBaseConfig {
*/ */
private Firewall firewall; private Firewall firewall;
/**
* shiro拦截排除
*/
private Shiro shiro;
/** /**
* 上传文件配置 * 上传文件配置
*/ */
@ -58,8 +62,12 @@ public class JeecgBaseConfig {
* @return * @return
*/ */
private WeiXinPay weiXinPay; private WeiXinPay weiXinPay;
/**
* 百度开放API配置
*/
private BaiduApi baiduApi;
public Elasticsearch getElasticsearch() { public Elasticsearch getElasticsearch() {
return elasticsearch; return elasticsearch;
} }
@ -84,6 +92,14 @@ public class JeecgBaseConfig {
this.signatureSecret = signatureSecret; this.signatureSecret = signatureSecret;
} }
public Shiro getShiro() {
return shiro;
}
public void setShiro(Shiro shiro) {
this.shiro = shiro;
}
public Path getPath() { public Path getPath() {
return path; return path;
} }
@ -131,5 +147,13 @@ public class JeecgBaseConfig {
public void setWeiXinPay(WeiXinPay weiXinPay) { public void setWeiXinPay(WeiXinPay weiXinPay) {
this.weiXinPay = weiXinPay; this.weiXinPay = weiXinPay;
} }
public BaiduApi getBaiduApi() {
return baiduApi;
}
public void setBaiduApi(BaiduApi baiduApi) {
this.baiduApi = baiduApi;
}
} }

View File

@ -0,0 +1,33 @@
package org.jeecg.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @Description: 短信模板
*
* @author: wangshuai
* @date: 2024/11/5 下午3:44
*/
@Data
@Component("jeecgSmsTemplateConfig")
@ConfigurationProperties(prefix = "jeecg.oss.sms-template")
public class JeecgSmsTemplateConfig {
/**
* 短信签名
*/
private String signature;
/**
* 短信模板code
*
* @return
*/
private Map<String,String> templateCode;
}

View File

@ -21,6 +21,12 @@ public class StaticConfig {
@Value(value = "${spring.mail.username:}") @Value(value = "${spring.mail.username:}")
private String emailFrom; private String emailFrom;
/**
* 是否开启定时发送
*/
@Value(value = "${spring.mail.timeJobSend:false}")
private Boolean timeJobSend;
// /** // /**
// * 签名密钥串 // * 签名密钥串
// */ // */

View File

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

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

View File

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

View File

@ -3,8 +3,8 @@ package org.jeecg.config.filter;
import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.CommonConstant;
import org.jeecg.config.sign.util.BodyReaderHttpServletRequestWrapper; import org.jeecg.config.sign.util.BodyReaderHttpServletRequestWrapper;
import jakarta.servlet.*; import javax.servlet.*;
import jakarta.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.IOException; 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.TokenUtils;
import org.jeecg.common.util.oConvertUtils; import org.jeecg.common.util.oConvertUtils;
import jakarta.servlet.*; import javax.servlet.*;
import jakarta.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
/** /**

View File

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

View File

@ -6,13 +6,13 @@ import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType; import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*; import org.apache.ibatis.plugin.*;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.config.TenantContext; import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.TenantConstant; import org.jeecg.common.constant.TenantConstant;
import org.jeecg.common.system.vo.LoginUser; import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SpringContextUtils; import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.TokenUtils; import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils; import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.security.utils.SecureUtil;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -192,7 +192,7 @@ public class MybatisInterceptor implements Interceptor {
private LoginUser getLoginUser() { private LoginUser getLoginUser() {
LoginUser sysUser = null; LoginUser sysUser = null;
try { try {
sysUser = SecureUtil.currentUser() != null ? SecureUtil.currentUser() : null; sysUser = SecurityUtils.getSubject().getPrincipal() != null ? (LoginUser) SecurityUtils.getSubject().getPrincipal() : null;
} catch (Exception e) { } catch (Exception e) {
//e.printStackTrace(); //e.printStackTrace();
sysUser = null; sysUser = null;

View File

@ -11,7 +11,7 @@ import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.config.mybatis.ThreadLocalDataHelper; import org.jeecg.config.mybatis.ThreadLocalDataHelper;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method; 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.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import jakarta.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; 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,39 +0,0 @@
package org.jeecg.config.security;
import io.undertow.servlet.spec.HttpServletRequestImpl;
import io.undertow.util.HttpString;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
/**
* 复制仪盘表请求query体携带的token
* @author eightmonth
* @date 2024/7/3 14:04
*/
@Component
@Order(value = Integer.MIN_VALUE)
public class CopyTokenFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// 以下为undertow定制代码如切换其它servlet容器需要同步更换
HttpServletRequestImpl undertowRequest = (HttpServletRequestImpl) request;
String bearerToken = request.getParameter("token");
String headerBearerToken = request.getHeader("X-Access-Token");
if (StringUtils.hasText(bearerToken)) {
undertowRequest.getExchange().getRequestHeaders().add(new HttpString("Authorization"), "bearer " + bearerToken);
} else if (StringUtils.hasText(headerBearerToken)) {
undertowRequest.getExchange().getRequestHeaders().add(new HttpString("Authorization"), "bearer " + headerBearerToken);
}
filterChain.doFilter(undertowRequest, response);
}
}

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.getId()));
Set<String> permissionList;
if (Objects.nonNull(cache)) {
permissionList = (Set<String>) cache;
} else {
permissionList = commonAPI.queryUserAuths(loginUser.getId());
redisUtil.set(buildKey("permission", loginUser.getId()), 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,264 +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/list")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/view")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher("/drag/onlDragDatasetHead/getLoginUser")).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("该用户已冻结");
}
}
}

View File

@ -1,19 +0,0 @@
package org.jeecg.config.security.self;
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不支持对外请求仅为程序内部生成token
* @author eightmonth
* @date 2024/3/19 11:37
*/
public class SelfAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
public SelfAuthenticationToken(Authentication clientPrincipal, Map<String, Object> additionalParameters) {
super(new AuthorizationGrantType(LoginType.SELF), clientPrincipal, additionalParameters);
}
}

View File

@ -1,81 +0,0 @@
package org.jeecg.config.security.social;
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;
/**
* 社交模式认证转换器配合github、企业微信、钉钉、微信登录使用
* @author EightMonth
* @date 2024/1/1
*/
@AllArgsConstructor
public class SocialGrantAuthenticationConvert implements AuthenticationConverter {
@Override
public Authentication convert(HttpServletRequest request) {
String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
if (!LoginType.SOCIAL.equals(grantType)) {
return null;
}
Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication();
//从request中提取请求参数然后存入MultiValueMap<String, String>
MultiValueMap<String, String> parameters = getParameters(request);
String token = parameters.getFirst("token");
if (!StringUtils.hasText(token)) {
throw new OAuth2AuthenticationException("无效请求三方token不能为空");
}
String source = parameters.getFirst("thirdType");
if (!StringUtils.hasText(source)) {
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 SocialGrantAuthenticationToken(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,276 +0,0 @@
package org.jeecg.config.security.social;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
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.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.config.security.password.PasswordGrantAuthenticationToken;
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.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;
/**
* 社交模式认证处理器负责处理该认证模式下的核心逻辑配合github、企业微信、钉钉、微信登录使用
* @author EightMonth
* @date 2024/1/1
*/
@Slf4j
public class SocialGrantAuthenticationProvider 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 SocialGrantAuthenticationProvider(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 {
SocialGrantAuthenticationToken socialGrantAuthenticationToken = (SocialGrantAuthenticationToken) authentication;
Map<String, Object> additionalParameter = socialGrantAuthenticationToken.getAdditionalParameters();
// 授权类型
AuthorizationGrantType authorizationGrantType = socialGrantAuthenticationToken.getGrantType();
// 三方token
String token = (String) additionalParameter.get("token");
// 三方来源
String source = (String) additionalParameter.get("thirdType");
//请求参数权限范围
String requestScopesStr = (String)additionalParameter.getOrDefault(OAuth2ParameterNames.SCOPE, "*");
//请求参数权限范围专场集合
Set<String> requestScopeSet = Stream.of(requestScopesStr.split(" ")).collect(Collectors.toSet());
DecodedJWT jwt = JWT.decode(token);
String username = jwt.getClaim("username").asString();
// 通过手机号获取用户信息
LoginUser loginUser = commonAPI.getUserByName(username);
// 检查用户可行性
checkUserIsEffective(loginUser);
OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient(socialGrantAuthenticationToken);
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);
}
//由于在上面已验证过用户名、密码现在构建一个已认证的对象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(socialGrantAuthenticationToken);
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 SocialGrantAuthenticationToken.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.social;
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使用配合github、企业微信、钉钉、微信登录使用
* @author EightMonth
* @date 2024/1/1
*/
public class SocialGrantAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
public SocialGrantAuthenticationToken(Authentication clientPrincipal, Map<String, Object> additionalParameters) {
super(new AuthorizationGrantType(LoginType.SOCIAL), clientPrincipal, additionalParameters);
}
}

View File

@ -1,23 +0,0 @@
package org.jeecg.config.security.utils;
import com.alibaba.fastjson2.JSONObject;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SpringContextUtils;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* 认证信息工具类
* @author EightMonth
* @date 2024/1/10 17:03
*/
public class SecureUtil {
/**
* 通过当前认证信息获取用户信息
* @return
*/
public static LoginUser currentUser() {
String name = SecurityContextHolder.getContext().getAuthentication().getName();
return JSONObject.parseObject(name, LoginUser.class);
}
}

View File

@ -0,0 +1,28 @@
package org.jeecg.config.shiro;
import org.apache.shiro.authc.AuthenticationToken;
/**
* @Author Scott
* @create 2018-07-12 15:19
* @desc
**/
public class JwtToken implements AuthenticationToken {
private static final long serialVersionUID = 1L;
private String token;
public JwtToken(String token) {
this.token = token;
}
@Override
public Object getPrincipal() {
return token;
}
@Override
public Object getCredentials() {
return token;
}
}

View File

@ -0,0 +1,364 @@
package org.jeecg.config.shiro;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.*;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.JeecgBaseConfig;
import org.jeecg.config.shiro.filters.CustomShiroFilterFactoryBean;
import org.jeecg.config.shiro.filters.JwtFilter;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.*;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.filter.DelegatingFilterProxy;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import javax.annotation.Resource;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author: Scott
* @date: 2018/2/7
* @description: shiro 配置类
*/
@Slf4j
@Configuration
public class ShiroConfig {
@Resource
private LettuceConnectionFactory lettuceConnectionFactory;
@Autowired
private Environment env;
@Resource
private JeecgBaseConfig jeecgBaseConfig;
@Autowired(required = false)
private RedisProperties redisProperties;
/**
* Filter Chain定义说明
*
* 1、一个URL可以配置多个Filter使用逗号分隔
* 2、当设置多个过滤器时全部验证通过才视为通过
* 3、部分过滤器可指定参数如permsroles
*/
@Bean("shiroFilterFactoryBean")
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
CustomShiroFilterFactoryBean shiroFilterFactoryBean = new CustomShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 拦截器
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
//支持yml方式配置拦截排除
if(jeecgBaseConfig!=null && jeecgBaseConfig.getShiro()!=null){
String shiroExcludeUrls = jeecgBaseConfig.getShiro().getExcludeUrls();
if(oConvertUtils.isNotEmpty(shiroExcludeUrls)){
String[] permissionUrl = shiroExcludeUrls.split(",");
for(String url : permissionUrl){
filterChainDefinitionMap.put(url,"anon");
}
}
}
// 配置不会被拦截的链接 顺序判断
filterChainDefinitionMap.put("/sys/cas/client/validateLogin", "anon"); //cas验证登录
filterChainDefinitionMap.put("/sys/randomImage/**", "anon"); //登录验证码接口排除
filterChainDefinitionMap.put("/sys/checkCaptcha", "anon"); //登录验证码接口排除
filterChainDefinitionMap.put("/sys/smsCheckCaptcha", "anon"); //短信次数发送太多验证码排除
filterChainDefinitionMap.put("/sys/login", "anon"); //登录接口排除
filterChainDefinitionMap.put("/sys/mLogin", "anon"); //登录接口排除
filterChainDefinitionMap.put("/sys/logout", "anon"); //登出接口排除
filterChainDefinitionMap.put("/sys/thirdLogin/**", "anon"); //第三方登录
filterChainDefinitionMap.put("/sys/getEncryptedString", "anon"); //获取加密串
filterChainDefinitionMap.put("/sys/sms", "anon");//短信验证码
filterChainDefinitionMap.put("/sys/phoneLogin", "anon");//手机登录
filterChainDefinitionMap.put("/sys/user/checkOnlyUser", "anon");//校验用户是否存在
filterChainDefinitionMap.put("/sys/user/register", "anon");//用户注册
filterChainDefinitionMap.put("/sys/user/phoneVerification", "anon");//用户忘记密码验证手机号
filterChainDefinitionMap.put("/sys/user/passwordChange", "anon");//用户更改密码
filterChainDefinitionMap.put("/auth/2step-code", "anon");//登录验证码
filterChainDefinitionMap.put("/sys/common/static/**", "anon");//图片预览 &下载文件不限制token
filterChainDefinitionMap.put("/sys/common/pdf/**", "anon");//pdf预览
//filterChainDefinitionMap.put("/sys/common/view/**", "anon");//图片预览不限制token
//filterChainDefinitionMap.put("/sys/common/download/**", "anon");//文件下载不限制token
filterChainDefinitionMap.put("/generic/**", "anon");//pdf预览需要文件
filterChainDefinitionMap.put("/sys/getLoginQrcode/**", "anon"); //登录二维码
filterChainDefinitionMap.put("/sys/getQrcodeToken/**", "anon"); //监听扫码
filterChainDefinitionMap.put("/sys/checkAuth", "anon"); //授权接口排除
//update-begin--Author:scott Date:20221116 for排除静态资源后缀
filterChainDefinitionMap.put("/", "anon");
filterChainDefinitionMap.put("/doc.html", "anon");
filterChainDefinitionMap.put("/**/*.js", "anon");
filterChainDefinitionMap.put("/**/*.css", "anon");
filterChainDefinitionMap.put("/**/*.html", "anon");
filterChainDefinitionMap.put("/**/*.svg", "anon");
filterChainDefinitionMap.put("/**/*.pdf", "anon");
filterChainDefinitionMap.put("/**/*.jpg", "anon");
filterChainDefinitionMap.put("/**/*.png", "anon");
filterChainDefinitionMap.put("/**/*.gif", "anon");
filterChainDefinitionMap.put("/**/*.ico", "anon");
filterChainDefinitionMap.put("/**/*.ttf", "anon");
filterChainDefinitionMap.put("/**/*.woff", "anon");
filterChainDefinitionMap.put("/**/*.woff2", "anon");
filterChainDefinitionMap.put("/**/*.glb", "anon");
filterChainDefinitionMap.put("/**/*.wasm", "anon");
//update-end--Author:scott Date:20221116 for排除静态资源后缀
filterChainDefinitionMap.put("/druid/**", "anon");
filterChainDefinitionMap.put("/swagger-ui.html", "anon");
filterChainDefinitionMap.put("/swagger**/**", "anon");
filterChainDefinitionMap.put("/webjars/**", "anon");
filterChainDefinitionMap.put("/v2/**", "anon");
// update-begin--Author:sunjianlei Date:20210510 for排除消息通告查看详情页面用于第三方APP
filterChainDefinitionMap.put("/sys/annountCement/show/**", "anon");
// update-end--Author:sunjianlei Date:20210510 for排除消息通告查看详情页面用于第三方APP
//积木报表排除
filterChainDefinitionMap.put("/jmreport/**", "anon");
filterChainDefinitionMap.put("/**/*.js.map", "anon");
filterChainDefinitionMap.put("/**/*.css.map", "anon");
//拖拽仪表盘设计器排除
filterChainDefinitionMap.put("/drag/view", "anon");
filterChainDefinitionMap.put("/drag/page/queryById", "anon");
filterChainDefinitionMap.put("/drag/page/addVisitsNumber", "anon");
filterChainDefinitionMap.put("/drag/page/queryTemplateList", "anon");
filterChainDefinitionMap.put("/drag/share/view/**", "anon");
filterChainDefinitionMap.put("/drag/onlDragDatasetHead/getAllChartData", "anon");
filterChainDefinitionMap.put("/drag/onlDragDatasetHead/getTotalData", "anon");
filterChainDefinitionMap.put("/drag/mock/json/**", "anon");
filterChainDefinitionMap.put("/jimubi/view", "anon");
filterChainDefinitionMap.put("/jimubi/share/view/**", "anon");
//大屏模板例子
filterChainDefinitionMap.put("/test/bigScreen/**", "anon");
filterChainDefinitionMap.put("/bigscreen/template1/**", "anon");
filterChainDefinitionMap.put("/bigscreen/template2/**", "anon");
//filterChainDefinitionMap.put("/test/jeecgDemo/rabbitMqClientTest/**", "anon"); //MQ测试
//filterChainDefinitionMap.put("/test/jeecgDemo/html", "anon"); //模板页面
//filterChainDefinitionMap.put("/test/jeecgDemo/redis/**", "anon"); //redis测试
//websocket排除
filterChainDefinitionMap.put("/websocket/**", "anon");//系统通知和公告
filterChainDefinitionMap.put("/newsWebsocket/**", "anon");//CMS模块
filterChainDefinitionMap.put("/vxeSocket/**", "anon");//JVxeTable无痕刷新示例
//性能监控——安全隐患泄露TOEKNdurid连接池也有
//filterChainDefinitionMap.put("/actuator/**", "anon");
//测试模块排除
filterChainDefinitionMap.put("/test/seata/**", "anon");
//错误路径排除
filterChainDefinitionMap.put("/error", "anon");
// 企业微信证书排除
filterChainDefinitionMap.put("/WW_verify*", "anon");
// 添加自己的过滤器并且取名为jwt
Map<String, Filter> filterMap = new HashMap<String, Filter>(1);
//如果cloudServer为空 则说明是单体 需要加载跨域配置【微服务跨域切换】
Object cloudServer = env.getProperty(CommonConstant.CLOUD_SERVER_KEY);
filterMap.put("jwt", new JwtFilter(cloudServer==null));
shiroFilterFactoryBean.setFilters(filterMap);
// <!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边
filterChainDefinitionMap.put("/**", "jwt");
// 未授权界面返回JSON
shiroFilterFactoryBean.setUnauthorizedUrl("/sys/common/403");
shiroFilterFactoryBean.setLoginUrl("/sys/common/403");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
//update-begin---author:chenrui ---date:20240126 for【QQYUN-7932】AI助手------------
/**
* spring过滤装饰器 <br/>
* 因为shiro的filter不支持异步请求,导致所有的异步请求都会报错. <br/>
* 所以需要用spring的FilterRegistrationBean再代理一下shiro的filter.为他扩展异步支持. <br/>
* 后续所有异步的接口都需要再这里增加registration.addUrlPatterns("/xxx/xxx");
* @return
* @author chenrui
* @date 2024/12/3 19:49
*/
@Bean
public FilterRegistrationBean shiroFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new DelegatingFilterProxy("shiroFilterFactoryBean"));
registration.setEnabled(true);
//update-begin---author:chenrui ---date:20241202 for[issues/7491]运行时间好长,效率慢 ------------
registration.addUrlPatterns("/test/ai/chat/send");
//update-end---author:chenrui ---date:20241202 for[issues/7491]运行时间好长,效率慢 ------------
//支持异步
registration.setAsyncSupported(true);
registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);
return registration;
}
//update-end---author:chenrui ---date:20240126 for【QQYUN-7932】AI助手------------
@Bean("securityManager")
public DefaultWebSecurityManager securityManager(ShiroRealm myRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myRealm);
/*
* 关闭shiro自带的session详情见文档
* http://shiro.apache.org/session-management.html#SessionManagement-
* StatelessApplications%28Sessionless%29
*/
DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
securityManager.setSubjectDAO(subjectDAO);
//自定义缓存实现,使用redis
securityManager.setCacheManager(redisCacheManager());
return securityManager;
}
/**
* 下面的代码是添加注解支持
* @return
*/
@Bean
@DependsOn("lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
/**
* 解决重复代理问题 github#994
* 添加前缀判断 不匹配 任何Advisor
*/
defaultAdvisorAutoProxyCreator.setUsePrefix(true);
defaultAdvisorAutoProxyCreator.setAdvisorBeanNamePrefix("_no_advisor");
return defaultAdvisorAutoProxyCreator;
}
@Bean
public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
/**
* cacheManager 缓存 redis实现
* 使用的是shiro-redis开源插件
*
* @return
*/
public RedisCacheManager redisCacheManager() {
log.info("===============(1)创建缓存管理器RedisCacheManager");
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
//redis中针对不同用户缓存(此处的id需要对应user实体中的id字段,用于唯一标识)
redisCacheManager.setPrincipalIdFieldName("id");
//用户权限信息缓存时间
redisCacheManager.setExpire(200000);
return redisCacheManager;
}
/**
* RedisConfig在项目starter项目中
* jeecg-boot-starter-github\jeecg-boot-common\src\main\java\org\jeecg\common\modules\redis\config\RedisConfig.java
*
* 配置shiro redisManager
* 使用的是shiro-redis开源插件
*
* @return
*/
@Bean
public IRedisManager redisManager() {
log.info("===============(2)创建RedisManager,连接Redis..");
IRedisManager manager;
// sentinel cluster redis【issues/5569】shiro集成 redis 不支持 sentinel 方式部署的redis集群 #5569
if (Objects.nonNull(redisProperties)
&& Objects.nonNull(redisProperties.getSentinel())
&& !CollectionUtils.isEmpty(redisProperties.getSentinel().getNodes())) {
RedisSentinelManager sentinelManager = new RedisSentinelManager();
sentinelManager.setMasterName(redisProperties.getSentinel().getMaster());
sentinelManager.setHost(String.join(",", redisProperties.getSentinel().getNodes()));
sentinelManager.setPassword(redisProperties.getPassword());
sentinelManager.setDatabase(redisProperties.getDatabase());
return sentinelManager;
}
// redis 单机支持,在集群为空,或者集群无机器时候使用 add by jzyadmin@163.com
if (lettuceConnectionFactory.getClusterConfiguration() == null || lettuceConnectionFactory.getClusterConfiguration().getClusterNodes().isEmpty()) {
RedisManager redisManager = new RedisManager();
redisManager.setHost(lettuceConnectionFactory.getHostName() + ":" + lettuceConnectionFactory.getPort());
//(lettuceConnectionFactory.getPort());
redisManager.setDatabase(lettuceConnectionFactory.getDatabase());
redisManager.setTimeout(0);
if (!StringUtils.isEmpty(lettuceConnectionFactory.getPassword())) {
redisManager.setPassword(lettuceConnectionFactory.getPassword());
}
manager = redisManager;
}else{
// redis集群支持优先使用集群配置
RedisClusterManager redisManager = new RedisClusterManager();
Set<HostAndPort> portSet = new HashSet<>();
lettuceConnectionFactory.getClusterConfiguration().getClusterNodes().forEach(node -> portSet.add(new HostAndPort(node.getHost() , node.getPort())));
//update-begin--Author:scott Date:20210531 for修改集群模式下未设置redis密码的bug issues/I3QNIC
if (oConvertUtils.isNotEmpty(lettuceConnectionFactory.getPassword())) {
JedisCluster jedisCluster = new JedisCluster(portSet, 2000, 2000, 5,
lettuceConnectionFactory.getPassword(), new GenericObjectPoolConfig());
redisManager.setPassword(lettuceConnectionFactory.getPassword());
redisManager.setJedisCluster(jedisCluster);
} else {
JedisCluster jedisCluster = new JedisCluster(portSet);
redisManager.setJedisCluster(jedisCluster);
}
//update-end--Author:scott Date:20210531 for修改集群模式下未设置redis密码的bug issues/I3QNIC
manager = redisManager;
}
return manager;
}
private List<String> rebuildUrl(String[] bases, String[] uris) {
List<String> urls = new ArrayList<>();
for (String base : bases) {
for (String uri : uris) {
urls.add(prefix(base)+prefix(uri));
}
}
return urls;
}
private String prefix(String seg) {
return seg.startsWith("/") ? seg : "/"+seg;
}
}

View File

@ -0,0 +1,234 @@
package org.jeecg.config.shiro;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.mybatis.MybatisPlusSaasConfig;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Set;
/**
* @Description: 用户登录鉴权和获取用户授权
* @Author: Scott
* @Date: 2019-4-23 8:13
* @Version: 1.1
*/
@Component
@Slf4j
public class ShiroRealm extends AuthorizingRealm {
@Lazy
@Resource
private CommonAPI commonApi;
@Lazy
@Resource
private RedisUtil redisUtil;
/**
* 必须重写此方法不然Shiro会报错
*/
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JwtToken;
}
/**
* 权限信息认证(包括角色以及权限)是用户访问controller的时候才进行验证(redis存储的此处权限信息)
* 触发检测用户权限时才会调用此方法例如checkRole,checkPermission
*
* @param principals 身份信息
* @return AuthorizationInfo 权限信息
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
log.debug("===============Shiro权限认证开始============ [ roles、permissions]==========");
String username = null;
String userId = null;
if (principals != null) {
LoginUser sysUser = (LoginUser) principals.getPrimaryPrincipal();
username = sysUser.getUsername();
userId = sysUser.getId();
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 设置用户拥有的角色集合比如“admin,test”
Set<String> roleSet = commonApi.queryUserRolesById(userId);
//System.out.println(roleSet.toString());
info.setRoles(roleSet);
// 设置用户拥有的权限集合比如“sys:role:add,sys:user:add”
Set<String> permissionSet = commonApi.queryUserAuths(userId);
info.addStringPermissions(permissionSet);
//System.out.println(permissionSet);
log.info("===============Shiro权限认证成功==============");
return info;
}
/**
* 用户信息认证是在用户进行登录的时候进行验证(不存redis)
* 也就是说验证用户输入的账号和密码是否正确,错误抛出异常
*
* @param auth 用户登录的账号密码信息
* @return 返回封装了用户信息的 AuthenticationInfo 实例
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
log.debug("===============Shiro身份认证开始============doGetAuthenticationInfo==========");
String token = (String) auth.getCredentials();
if (token == null) {
HttpServletRequest req = SpringContextUtils.getHttpServletRequest();
log.info("————————身份认证失败——————————IP地址: "+ oConvertUtils.getIpAddrByRequest(req) +"URL:"+req.getRequestURI());
throw new AuthenticationException("token为空!");
}
// 校验token有效性
LoginUser loginUser = null;
try {
loginUser = this.checkUserTokenIsEffect(token);
} catch (AuthenticationException e) {
JwtUtil.responseError(SpringContextUtils.getHttpServletResponse(),401,e.getMessage());
e.printStackTrace();
return null;
}
return new SimpleAuthenticationInfo(loginUser, token, getName());
}
/**
* 校验token的有效性
*
* @param token
*/
public LoginUser checkUserTokenIsEffect(String token) throws AuthenticationException {
// 解密获得username用于和数据库进行对比
String username = JwtUtil.getUsername(token);
if (username == null) {
throw new AuthenticationException("token非法无效!");
}
// 查询用户信息
log.debug("———校验token是否有效————checkUserTokenIsEffect——————— "+ token);
LoginUser loginUser = TokenUtils.getLoginUser(username, commonApi, redisUtil);
//LoginUser loginUser = commonApi.getUserByName(username);
if (loginUser == null) {
throw new AuthenticationException("用户不存在!");
}
// 判断用户状态
if (loginUser.getStatus() != 1) {
throw new AuthenticationException("账号已被锁定,请联系管理员!");
}
// 校验token是否超时失效 & 或者账号密码是否错误
if (!jwtTokenRefresh(token, username, loginUser.getPassword())) {
throw new AuthenticationException(CommonConstant.TOKEN_IS_INVALID_MSG);
}
//update-begin-author:taoyan date:20210609 for:校验用户的tenant_id和前端传过来的是否一致
String userTenantIds = loginUser.getRelTenantIds();
if(MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL && oConvertUtils.isNotEmpty(userTenantIds)){
String contextTenantId = TenantContext.getTenant();
log.debug("登录租户:" + contextTenantId);
log.debug("用户拥有那些租户:" + userTenantIds);
//登录用户无租户前端header中租户ID值为 0
String str ="0";
if(oConvertUtils.isNotEmpty(contextTenantId) && !str.equals(contextTenantId)){
//update-begin-author:taoyan date:20211227 for: /issues/I4O14W 用户租户信息变更判断漏洞
String[] arr = userTenantIds.split(",");
if(!oConvertUtils.isIn(contextTenantId, arr)){
boolean isAuthorization = false;
//========================================================================
// 查询用户信息(如果租户不匹配从数据库中重新查询一次用户信息)
String loginUserKey = CacheConstant.SYS_USERS_CACHE + "::" + username;
redisUtil.del(loginUserKey);
LoginUser loginUserFromDb = commonApi.getUserByName(username);
if (oConvertUtils.isNotEmpty(loginUserFromDb.getRelTenantIds())) {
String[] newArray = loginUserFromDb.getRelTenantIds().split(",");
if (oConvertUtils.isIn(contextTenantId, newArray)) {
isAuthorization = true;
}
}
//========================================================================
//*********************************************
if(!isAuthorization){
log.info("租户异常——登录租户:" + contextTenantId);
log.info("租户异常——用户拥有租户组:" + userTenantIds);
throw new AuthenticationException("登录租户授权变更,请重新登陆!");
}
//*********************************************
}
//update-end-author:taoyan date:20211227 for: /issues/I4O14W 用户租户信息变更判断漏洞
}
}
//update-end-author:taoyan date:20210609 for:校验用户的tenant_id和前端传过来的是否一致
return loginUser;
}
/**
* JWTToken刷新生命周期 (实现: 用户在线操作不掉线功能)
* 1、登录成功后将用户的JWT生成的Token作为k、v存储到cache缓存里面(这时候k、v值一样)缓存有效期设置为Jwt有效时间的2倍
* 2、当该用户再次请求时通过JWTFilter层层校验之后会进入到doGetAuthenticationInfo进行身份验证
* 3、当该用户这次请求jwt生成的token值已经超时但该token对应cache中的k还是存在则表示该用户一直在操作只是JWT的token失效了程序会给token对应的k映射的v值重新生成JWTToken并覆盖v值该缓存生命周期重新计算
* 4、当该用户这次请求jwt在生成的token值已经超时并在cache中不存在对应的k则表示该用户账户空闲超时返回用户信息已失效请重新登录。
* 注意: 前端请求Header中设置Authorization保持不变校验有效性以缓存中的token为准。
* 用户过期时间 = Jwt有效时间 * 2。
*
* @param userName
* @param passWord
* @return
*/
public boolean jwtTokenRefresh(String token, String userName, String passWord) {
String cacheToken = String.valueOf(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token));
if (oConvertUtils.isNotEmpty(cacheToken)) {
// 校验token有效性
if (!JwtUtil.verify(cacheToken, userName, passWord)) {
String newAuthorization = JwtUtil.sign(userName, passWord);
// 设置超时时间
redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization);
redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME *2 / 1000);
log.debug("——————————用户在线操作更新token保证不掉线—————————jwtTokenRefresh——————— "+ token);
}
//update-begin--Author:scott Date:20191005 for解决每次请求都重写redis中 token缓存问题
// else {
// // 设置超时时间
// redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken);
// redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
// }
//update-end--Author:scott Date:20191005 for解决每次请求都重写redis中 token缓存问题
return true;
}
//redis中不存在此TOEKN说明token非法返回false
return false;
}
/**
* 清除当前用户的权限认证缓存
*
* @param principals 权限信息
*/
@Override
public void clearCache(PrincipalCollection principals) {
super.clearCache(principals);
//update-begin---author:scott ---date::2024-06-18 for【TV360X-1320】分配权限必须退出重新登录才生效造成很多用户困扰---
super.clearCachedAuthorizationInfo(principals);
//update-end---author:scott ---date::2024-06-18 for【TV360X-1320】分配权限必须退出重新登录才生效造成很多用户困扰---
}
}

View File

@ -0,0 +1,77 @@
package org.jeecg.config.shiro.filters;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.InvalidRequestFilter;
import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.apache.shiro.mgt.SecurityManager;
import org.springframework.beans.factory.BeanInitializationException;
import javax.servlet.Filter;
import java.util.Map;
/**
* 自定义ShiroFilterFactoryBean解决资源中文路径问题
* @author: jeecg-boot
*/
@Slf4j
public class CustomShiroFilterFactoryBean extends ShiroFilterFactoryBean {
@Override
public Class getObjectType() {
return MySpringShiroFilter.class;
}
@Override
protected AbstractShiroFilter createInstance() throws Exception {
SecurityManager securityManager = getSecurityManager();
if (securityManager == null) {
String msg = "SecurityManager property must be set.";
throw new BeanInitializationException(msg);
}
if (!(securityManager instanceof WebSecurityManager)) {
String msg = "The security manager does not implement the WebSecurityManager interface.";
throw new BeanInitializationException(msg);
}
FilterChainManager manager = createFilterChainManager();
//Expose the constructed FilterChainManager by first wrapping it in a
// FilterChainResolver implementation. The AbstractShiroFilter implementations
// do not know about FilterChainManagers - only resolvers:
PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver();
chainResolver.setFilterChainManager(manager);
Map<String, Filter> filterMap = manager.getFilters();
Filter invalidRequestFilter = filterMap.get(DefaultFilter.invalidRequest.name());
if (invalidRequestFilter instanceof InvalidRequestFilter) {
//此处是关键,设置false跳过URL携带中文400servletPath中文校验bug
((InvalidRequestFilter) invalidRequestFilter).setBlockNonAscii(false);
}
//Now create a concrete ShiroFilter instance and apply the acquired SecurityManager and built
//FilterChainResolver. It doesn't matter that the instance is an anonymous inner class
//here - we're just using it because it is a concrete AbstractShiroFilter instance that accepts
//injection of the SecurityManager and FilterChainResolver:
return new MySpringShiroFilter((WebSecurityManager) securityManager, chainResolver);
}
private static final class MySpringShiroFilter extends AbstractShiroFilter {
protected MySpringShiroFilter(WebSecurityManager webSecurityManager, FilterChainResolver resolver) {
if (webSecurityManager == null) {
throw new IllegalArgumentException("WebSecurityManager property cannot be null.");
} else {
this.setSecurityManager(webSecurityManager);
if (resolver != null) {
this.setFilterChainResolver(resolver);
}
}
}
}
}

View File

@ -0,0 +1,130 @@
package org.jeecg.config.shiro.filters;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.shiro.JwtToken;
import org.jeecg.config.shiro.ignore.InMemoryIgnoreAuth;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Description: 鉴权登录拦截器
* @Author: Scott
* @Date: 2018/10/7
**/
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {
/**
* 默认开启跨域设置(使用单体)
* 微服务情况下此属性设置为false
*/
private boolean allowOrigin = true;
public JwtFilter(){}
public JwtFilter(boolean allowOrigin){
this.allowOrigin = allowOrigin;
}
/**
* 执行登录认证
*
* @param request
* @param response
* @param mappedValue
* @return
*/
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
try {
// 判断当前路径是不是注解了@IngoreAuth路径如果是则放开验证
if (InMemoryIgnoreAuth.contains(((HttpServletRequest) request).getServletPath())) {
return true;
}
executeLogin(request, response);
return true;
} catch (Exception e) {
JwtUtil.responseError(response,401,CommonConstant.TOKEN_IS_INVALID_MSG);
return false;
//throw new AuthenticationException("Token失效请重新登录", e);
}
}
/**
*
*/
@Override
protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String token = httpServletRequest.getHeader(CommonConstant.X_ACCESS_TOKEN);
// update-begin--Author:lvdandan Date:20210105 forJT-355 OA聊天添加token验证获取token参数
if (oConvertUtils.isEmpty(token)) {
token = httpServletRequest.getParameter("token");
}
// update-end--Author:lvdandan Date:20210105 forJT-355 OA聊天添加token验证获取token参数
JwtToken jwtToken = new JwtToken(token);
// 提交给realm进行登入如果错误他会抛出异常并被捕获
getSubject(request, response).login(jwtToken);
// 如果没有抛出异常则代表登入成功返回true
return true;
}
/**
* 对跨域提供支持
*/
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
if(allowOrigin){
httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, httpServletRequest.getHeader(HttpHeaders.ORIGIN));
// 允许客户端请求方法
httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,OPTIONS,PUT,DELETE");
// 允许客户端提交的Header
String requestHeaders = httpServletRequest.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);
if (StringUtils.isNotEmpty(requestHeaders)) {
httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders);
}
// 允许客户端携带凭证信息(是否允许发送Cookie)
httpServletResponse.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
}
// 跨域时会首先发送一个option请求这里我们给option请求直接返回正常状态
if (RequestMethod.OPTIONS.name().equalsIgnoreCase(httpServletRequest.getMethod())) {
httpServletResponse.setStatus(HttpStatus.OK.value());
return false;
}
//update-begin-author:taoyan date:20200708 for:多租户用到
String tenantId = httpServletRequest.getHeader(CommonConstant.TENANT_ID);
TenantContext.setTenant(tenantId);
//update-end-author:taoyan date:20200708 for:多租户用到
return super.preHandle(request, response);
}
/**
* JwtFilter中ThreadLocal需要及时清除 #3634
*
* @param request
* @param response
* @param exception
* @throws Exception
*/
@Override
public void afterCompletion(ServletRequest request, ServletResponse response, Exception exception) throws Exception {
//log.info("------清空线程中多租户的ID={}------",TenantContext.getTenant());
TenantContext.clear();
}
}

View File

@ -0,0 +1,67 @@
package org.jeecg.config.shiro.filters;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import lombok.extern.slf4j.Slf4j;
/**
* @Author Scott
* @create 2019-02-01 15:56
* @desc 鉴权请求URL访问权限拦截器
*/
@Slf4j
public class ResourceCheckFilter extends AccessControlFilter {
private String errorUrl;
public String getErrorUrl() {
return errorUrl;
}
public void setErrorUrl(String errorUrl) {
this.errorUrl = errorUrl;
}
/**
* 表示是否允许访问 如果允许访问返回true否则false
*
* @param servletRequest
* @param servletResponse
* @param o 表示写在拦截器中括号里面的字符串 mappedValue 就是 [urls] 配置中拦截器参数部分
* @return
* @throws Exception
*/
@Override
protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
Subject subject = getSubject(servletRequest, servletResponse);
String url = getPathWithinApplication(servletRequest);
log.info("当前用户正在访问的 url => " + url);
return subject.isPermitted(url);
}
/**
* onAccessDenied表示当访问拒绝时是否已经处理了 如果返回 true 表示需要继续处理; 如果返回 false
* 表示该拦截器实例已经处理了,将直接返回即可。
*
* @param servletRequest
* @param servletResponse
* @return
* @throws Exception
*/
@Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
log.info("当 isAccessAllowed 返回 false 的时候,才会执行 method onAccessDenied ");
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.sendRedirect(request.getContextPath() + this.errorUrl);
// 返回 false 表示已经处理,例如页面跳转啥的,表示不在走以下的拦截器了(如果还有配置的话)
return false;
}
}

View File

@ -3,21 +3,16 @@ package org.jeecg.config.shiro.ignore;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.jeecg.config.shiro.IgnoreAuth; import org.jeecg.config.shiro.IgnoreAuth;
import org.springframework.aop.framework.Advised; import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
/** /**
* 在spring boot初始化时根据@RestController注解获取当前spring容器中的bean * 在spring boot初始化时根据@RestController注解获取当前spring容器中的bean
@ -27,32 +22,25 @@ import java.util.*;
@Slf4j @Slf4j
@Component @Component
@AllArgsConstructor @AllArgsConstructor
public class IgnoreAuthPostProcessor implements ApplicationListener<ContextRefreshedEvent> { public class IgnoreAuthPostProcessor implements InitializingBean {
private RequestMappingHandlerMapping requestMappingHandlerMapping;
private ApplicationContext applicationContext;
@Override @Override
public void onApplicationEvent(ContextRefreshedEvent event) { public void afterPropertiesSet() throws Exception {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
List<String> ignoreAuthUrls = new ArrayList<>(); List<String> ignoreAuthUrls = new ArrayList<>();
if (event.getApplicationContext().getParent() == null) { Set<Class<?>> restControllers = requestMappingHandlerMapping.getHandlerMethods().values().stream().map(HandlerMethod::getBeanType).collect(Collectors.toSet());
// 只处理根应用上下文的事件,避免在子上下文中重复处理 for (Class<?> restController : restControllers) {
Map<String, Object> restControllers = applicationContext.getBeansWithAnnotation(RestController.class); ignoreAuthUrls.addAll(postProcessRestController(restController));
for (Object restController : restControllers.values()) {
// 如 online系统的controller并不是spring 默认生成
if (restController instanceof Advised) {
ignoreAuthUrls.addAll(postProcessRestController(restController));
}
}
} }
log.info("Init Token ignoreAuthUrls Config [ 集合 ] {}", ignoreAuthUrls); log.info("Init Token ignoreAuthUrls Config [ 集合 ] {}", ignoreAuthUrls);
if (!CollectionUtils.isEmpty(ignoreAuthUrls)) { if (!CollectionUtils.isEmpty(ignoreAuthUrls)) {
InMemoryIgnoreAuth.set(ignoreAuthUrls); InMemoryIgnoreAuth.set(ignoreAuthUrls);
// 添加免登录url
addIgnoreUrl(ignoreAuthUrls);
} }
// 计算方法的耗时 // 计算方法的耗时
@ -61,9 +49,8 @@ public class IgnoreAuthPostProcessor implements ApplicationListener<ContextRefre
log.info("Init Token ignoreAuthUrls Config [ 耗时 ] " + elapsedTime + "毫秒"); log.info("Init Token ignoreAuthUrls Config [ 耗时 ] " + elapsedTime + "毫秒");
} }
private List<String> postProcessRestController(Object restController) { private List<String> postProcessRestController(Class<?> clazz) {
List<String> ignoreAuthUrls = new ArrayList<>(); List<String> ignoreAuthUrls = new ArrayList<>();
Class<?> clazz = ((Advised) restController).getTargetClass();
RequestMapping base = clazz.getAnnotation(RequestMapping.class); RequestMapping base = clazz.getAnnotation(RequestMapping.class);
String[] baseUrl = Objects.nonNull(base) ? base.value() : new String[]{}; String[] baseUrl = Objects.nonNull(base) ? base.value() : new String[]{};
Method[] methods = clazz.getDeclaredMethods(); Method[] methods = clazz.getDeclaredMethods();
@ -118,28 +105,4 @@ public class IgnoreAuthPostProcessor implements ApplicationListener<ContextRefre
private String prefix(String seg) { private String prefix(String seg) {
return seg.startsWith("/") ? seg : "/"+seg; return seg.startsWith("/") ? seg : "/"+seg;
} }
private void addIgnoreUrl(List<String> urls){
FilterChainProxy obj = applicationContext.getBean(FilterChainProxy.class);
if (Objects.isNull(obj)) {
return;
}
List<SecurityFilterChain> filterChains = (List<SecurityFilterChain>) getProperty(obj,"filterChains");
if (!CollectionUtils.isEmpty(filterChains)) {
for (String url : urls) {
filterChains.add(0, new DefaultSecurityFilterChain(new AntPathRequestMatcher(url, null)));
}
}
}
private Object getProperty(Object obj, String fieldName) {
try {
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(obj);
} catch (Exception e) {
return null;
}
}
} }

View File

@ -10,7 +10,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import jakarta.annotation.Resource; import javax.annotation.Resource;
/** /**
* 签名 拦截器配置 * 签名 拦截器配置

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