提交 7e85da9a 编写于 作者: A00028's avatar A00028

Initial commit

上级
流水线 #35209 已失败 ,包含阶段
in 9 minute 和 16 second

要显示的变更太多。

为了保持性能,仅显示文件中的 1000/1000+。

# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/guns-8.3.0-jdk17.iml" filepath="$PROJECT_DIR$/.idea/guns-8.3.0-jdk17.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
# Guns 8企业版
## 版本号:v8.3.3 发布时间:2025年2月27日
## 版本号:v8.3.2 发布时间:2024年12月4日
## 版本号:v8.3.0(完善micro插件) 发布时间:2024年10月14日
## 版本号:v8.3.0 发布时间:2024年9月25日
## 后端启动说明:
1. 打开`enterprise-plugins`文件夹,执行mvn clean install命令,将企业版插件核心包安装到本地仓库
2. 打开`guns-ent-backend-8.3.3`启动后端即可
## 前端启动说明:
1. 进入到目录`guns-ent-front-8.3.3`,推荐node用20.x版本
2. 执行`yarn`命令,安装依赖
3. 执行`yarn run dev`命令,即可启动项目
## 特别注意:
启动后台项目,需要检查idea的maven本地仓库路径,否则启动不起来后台项目
启动前端项目,node需要是20.x版本,yarn用最新版即可
\ No newline at end of file
*.class
# Package Files #
*.jar
*.war
*.ear
target/
# eclipse
.settings/
.classpath
.project
logs/
# idea
.idea/
*.iml
*velocity.log*
### STS ###
.apt_generated
.factorypath
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/
*.log
tmp/
\ No newline at end of file
---
title: Oracle适配
author: AndrewFeng,stylefeng
---
## oracle安装
### 1.拉取oracle镜像
```shell
docker pull marcocimatti/oracle12.2.0.1-se2
```
### 2.启动oracle容器
```shell
docker run -p 1521:1521 --name oracle12.2se2 -e ORACLE_PWD=guns123456 -d marcocimatti/oracle12.2.0.1-se2
```
![](./.1_oracle_images/fa9466ae.png)
### 3.启动过程比较慢,logs查看进度
```shell
docker logs -f oracle12.2se2
```
![](./.1_oracle_images/2528fa4d.png)
### 4.查看容器是否启动成功
检查是否为up状态,大概8分钟启动成功。
```shell
docker ps -a
```
![](./.1_oracle_images/d839947e.png)
### 5.navicat测试外网连接
navicat15下载地址: 链接:[https://pan.baidu.com/s/19XYTg9bVrwRAbDQ5U82Ecw](https://pan.baidu.com/s/19XYTg9bVrwRAbDQ5U82Ecw)
提取码:xjf4
![](./.1_oracle_images/2744c4e7.png)
### 6.右键数据库连接,打开命令行界面
有可能提示需要sqlplus.exe,sqlplus下载地址: 链接:[https://pan.baidu.com/s/1WIxj5WSteH9eQThWwmo4bg](https://pan.baidu.com/s/1WIxj5WSteH9eQThWwmo4bg)
提取码:0sus
### 7.创建表空间
```shell
create tablespace guns datafile '/opt/oracle/guns.dbf' size 500M AUTOEXTEND ON NEXT 50M MAXSIZE 20480M EXTENT MANAGEMENT LOCAL;
```
![](./.1_oracle_images/ddafc0d5.png)
### 8.创建用户guns,并赋予默认表空间guns
```shell
CREATE USER guns IDENTIFIED BY guns123456 DEFAULT TABLESPACE guns;
```
![](./.1_oracle_images/61abb3e4.png)
### 9.授权guns用户权限
```sql
GRANT DBA,CONNECT,RESOURCE TO guns;
```
![](./.1_oracle_images/4ea42809.png)
### 10.测试新用户连通
![](./.1_oracle_images/5b6dce64.png)
## Guns程序适配
### 1.pom中用加入oracle驱动
```xml
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
```
### 2.更改连接配置
先修改application.yml的配置,将flyway的开关改为关闭:
```yml
spring:
flyway:
enabled: false
```
打开application-local.yml,修改为oracle的相关配置
```yml
#Oracle配置
spring:
datasource:
driverClassName: oracle.jdbc.OracleDriver
url: jdbc:oracle:thin:@//127.0.0.1:1521/ORCLPDB1
username: guns
password: guns123456
# 连接池大小根据实际情况调整
maxActive: 100
maxPoolPreparedStatementPerConnectionSize: 100
```
修改配置之后,将db文件夹移动到项目的resources目录中。
### 3.启动程序
启动GunsApplication,flyway会自动初始化脚本。
![](./.1_oracle_images/adb0d3b9.png)
### 4. 图标问题
如果进去背景和图标看不到,则自行上传一个图标等图片在主题管理中。
![](.1_oracle_images/63b57396.png)
\ No newline at end of file
## 攻略:制作初始化脚本过程
### 1.打开navicat,找到mysql的库,右键选择逆向数据库到模型
![](./.2_oracle_step_images/03341f18.png)
### 2.选择 文件->模型转化为
![](.2_oracle_step_images/dbf8bf1e.png)
### 3.选择oracle 12c
![](.2_oracle_step_images/4c98b13c.png)
### 4.选择导出sql
![](.2_oracle_step_images/ce8a6701.png)
### 5.选择导出路径,确认导出
![](.2_oracle_step_images/59ab17db.png)
### 6.导出脚本成功
![](.2_oracle_step_images/26888698.png)
### 6.将脚本中的双引号全部去掉,否则会有大小写问题
![](.2_oracle_step_images/5dd73901.png)
### 7.关于数据的迁移
数据的迁移,可以通过navicat在线录入功能。
![](.2_oracle_step_images/75ac5051.png)
![](.2_oracle_step_images/0926ff74.png)
### 8. 脚本上的COPY_字样去掉
### 9. del_flag没加默认值,所有找到所有表都要加上默认值N
变为如下就行:
```sql
del_flag NCHAR(1) DEFAULT 'N' NOT NULL,
```
### 10. theme表有json,json中需要加上双引号(检查一下防止误删双引号)
### 11. 文件表的三个文件,字符串过长无法上传
需要改为拼接的方式进行,目前找到的方案如下:
```sql
DECLARE
buf BLOB;
BEGIN
dbms_lob.createtemporary(buf, FALSE);
dbms_lob.append(buf, HEXTORAW('0EC1D7FA6B411DA58149'));
--...lots of hex data...
dbms_lob.append(buf, HEXTORAW('0EC1D7FA6B411DA58149'));
UPDATE MyTable
SET blobData = buf
WHERE ID = 123;
END;
```
## 其他攻略:oracle mapping文件适配
sql编写时,尽量使用4种数据都认可的语法
### 1.|| 改为 or
编写sql时, || 在mysql中是或的意思,但是使用or可以兼容性更好
## 2.like字符串拼接
在mysql中,like经常和concat函数使用
例如:
```sql
#
mysql
like concat('%',
#{sysUserRequest.statusFlag},
'%'
)
```
但是在oracle中,不能用concat拼接了,需要改为||连接符
```sql
#
oracle
like '%' ||
#{sysUserRequest.statusFlag}
||
'%'
```
## 3.时间查询条件
以前直接拼装的字符串类型的时间查询条件,现在要改为Date类型,不能拼接字符串
```java
queryWrapper.between(ObjectUtil.isAllNotEmpty(beginDateTime,endDateTime),SysLog::getCreateTime,beginDateTime+" 00:00:00",endDateTime+" 23:59:59");
```
### 4.file和user都是oracle关键字
file和user都是oracle关键字,尽量在sql中不要用,如果必须用,需要用""双引号包起来
\ No newline at end of file
因为 它太大了无法显示 源差异 。您可以改为 查看blob。
## Postgre Sql安装
navicat15下载地址: 链接:https://pan.baidu.com/s/19XYTg9bVrwRAbDQ5U82Ecw
提取码:xjf4
### 1.拉取pgsql镜像
```shell
docker pull postgres:12
```
### 2.检查现有镜像
```shell
docker images
```
![](./.2_pgsql_images/f6df2ebb.png)
### 3.启动postgres容器
```shell
docker run -d --name pgsql12 -p 54322:5432 -e "POSTGRES_PASSWORD=123456" postgres:12
```
### 4.查看容器是否启动成功
```shell
docker ps -a
```
![](./.2_pgsql_images/4c5d531c.png)
### 5.navicat测试外网连接
密码是123456
![](./.2_pgsql_images/04103ae6.png)
### 6.新建一个guns库
![](./.2_pgsql_images/f653cfbf.png)
## Guns程序适配
### 1.pom中用进入postgre sql驱动
```xml
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5</version>
</dependency>
```
### 2.更改连接配置
打开application-local.yml,修改为pgsql的相关配置
```yml
#PostgreSQL配置
spring:
datasource:
driverClassName: org.postgresql.Driver
url: jdbc:postgresql://10.40.94.114:54322/guns
username: postgres
password: 123456
# 连接池大小根据实际情况调整
max-active: 100
max-pool-prepared-statement-per-connection-size: 100
flyway:
locations: classpath:db/migration/pgsql
```
修改配置之后,将db文件夹移动到项目的resources目录中。
### 3.启动程序
启动GunsApplication,flyway会自动初始化脚本。
## pgsql适配问题
使用navicat15,通过数据传输功能,可以迁移从mysql转义到pgsql
## 默认值问题
脚本转化过程中后,mysql中有默认值的设置,在pgsql脚本中没设置得手动设置
\ No newline at end of file
## Sql Server安装
navicat15下载地址: 链接:https://pan.baidu.com/s/1dAC56kft0bF4wF9yKScTdw?pwd=8qsy
提取码:8qsy
### 1.拉取sql server镜像
```shell
docker pull mcr.microsoft.com/mssql/server:2017-latest
```
### 2.查看镜像是否拉取成功
```shell
docker images
```
![](./.3_sqlserver_images/b31c66f4.png)
### 3.启动sql server容器
这里注意,密码不能设置太简单,否则启动不成功,需要最少8位,大小写字母数字都有
```shell
docker run -d --name sqlserver2017 -p 1433:1433 -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=Abcd1234" mcr.microsoft.com/mssql/server:2017-latest
```
### 4.查看容器是否启动成功
```shell
docker ps -a
```
![](./.3_sqlserver_images/6849a3b2.png)
### 5.navicat连接数据库
![](./.3_sqlserver_images/cf829304.png)
如果navicat连接提示错误:连接SQL Server出现 未发现数据源名称并且未指定默认驱动
解决方式:安装navicat自带sqlncli_x64.msi,就在安装目录下,安装后问题解决
![](./.3_sqlserver_images/29bbced2.png)
navicat15下载地址: 链接:https://pan.baidu.com/s/1dAC56kft0bF4wF9yKScTdw?pwd=8qsy
提取码:8qsy
### 6.新建guns数据库
右键连接,选择新建数据库:
![](./.3_sqlserver_images/52b87a45.png)
新建之后的库:
![](./.3_sqlserver_images/7b448412.png)
## Guns程序适配
### 1.pom中用进入sql server驱动
```xml
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
```
### 2.更改连接配置
打开application-local.yml,修改为oracle的相关配置
```yml
# Sql Server数据库
spring:
datasource:
driverClassName: net.sourceforge.jtds.jdbc.Driver
url: jdbc:jtds:sqlserver://10.40.94.112:1433;DatabaseName=guns
username: sa
password: "Abcd1234"
# 连接池大小根据实际情况调整
max-active: 100
max-pool-prepared-statement-per-connection-size: 100
flyway:
locations: classpath:db/migration/sqlserver
```
修改配置之后,将db文件夹移动到项目的resources目录中。
### 3.启动程序
启动GunsApplication,flyway会自动初始化脚本。
![](./.1_oracle_images/adb0d3b9.png)
### 4.文件找不到报错
如果报错文件找不到 在主题管理和个人信息,把相关图片都从新替换一下即可
![](.3_sqlserver_images/6ad1595b.png)
## Sql Server脚本的制作
使用navicat15,通过数据传输功能,可以迁移从mysql转义到sql server
## 默认值问题
脚本转化过程中后,mysql中有默认值的设置,在pgsql脚本中没设置得手动设置
## 程序适配问题
sql server中,select count(1) 之后不能跟order by,否则会报错
```sql
# 错误写法
select count(1) from users order by status
```
## like语句
like语句,内容中包含[]的,sql server可能会识别为关键字,所以要转义一下
```sql
# 之前的写法
like CONCAT('%[',#{sysUserRequest.orgId},']%')
# 新的写法
like CONCAT('%$[',#{sysUserRequest.orgId},'$]%') escape '$'
```
并且,这么写之后mysql也完全兼容,所以mysql和sql server的语句一般都可以用一套
注意:escape '$'一定要写在concat函数后边
\ No newline at end of file
## 人大金仓数据库
人大金仓数据库和pgsql基本一致
## SQL脚本初始化
还是先准备一个mysql数据库,让Guns自动初始化它完毕后
使用navicat15,通过数据传输功能,可以迁移从mysql转义到海量数据库
**脚本转化过程中后,mysql中有默认值的设置,在pgsql脚本中没设置得手动设置**
## 数据库连接
使用navicat 创建pgsql的连接即可
![](.readme_images/7d508f42.png)
新建一个guns库
![](.readme_images/f653cfbf.png)
**将`人大金仓-sql初始化脚本.sql`执行并导入到这个库中**
## Guns程序适配
### 1.pom中用进入人大金仓驱动
```xml
<!--人大金仓-->
<dependency>
<groupId>cn.com.kingbase</groupId>
<artifactId>kingbase8</artifactId>
<version>8.6.0</version>
</dependency>
```
### 2.更改连接配置
**关闭`application.yml`中的flyway的配置开关,设置为**
```yml
spring:
flyway:
enabled: false
```
打开`application-local.yml`修改为海量数据库的连接配置
```yml
#人大金仓配置
spring:
datasource:
driverClassName: com.kingbase8.Driver
url: jdbc:kingbase8://172.39.187.62:54321/test
username: system
password: 12345678ab
# 连接池大小根据实际情况调整
maxActive: 100
maxPoolPreparedStatementPerConnectionSize: 100
```
### 3.启动程序
启动GunsApplication即可
## openGauss
openGauss数据库适配和pgsql基本一致
## SQL脚本初始化
还是先准备一个mysql数据库,让Guns自动初始化它完毕后
使用navicat15,通过数据传输功能,可以迁移从mysql转义到openGauss
**脚本转化过程中后,mysql中有默认值的设置,在pgsql脚本中没设置得手动设置**
## 数据库连接
使用navicat 创建pgsql的连接即可
账号密码和数据库写您安装数据库时候的配置即可
![](.readme_images/0fd02949.png)
新建一个guns库
![](.readme_images/db11160b.png)
**将`openGauss-初始化脚本.sql`执行并导入到这个库中**
## Guns程序适配
### 1.pom中需要使用openGauss的数据库连接驱动
```xml
<dependency>
<groupId>org.opengauss</groupId>
<artifactId>opengauss-jdbc</artifactId>
<version>5.0.0-og</version>
</dependency>
```
### 2.更改连接配置
**关闭`application.yml`中的flyway的配置开关,设置为**
```yml
spring:
flyway:
enabled: false
```
打开`application-local.yml`修改为海量数据库的连接配置
```yml
# openGauss数据库配置
spring:
datasource:
driver-class-name: org.opengauss.Driver
url: jdbc:opengauss://192.168.31.228:5432/omm
username: gaussdb
password: Enmo@123
# 连接池大小根据实际情况调整
maxActive: 100
maxPoolPreparedStatementPerConnectionSize: 100
```
### 3.启动程序
启动GunsApplication即可
## 海量数据库
海量数据库适配和pgsql基本一致
## SQL脚本初始化
还是先准备一个mysql数据库,让Guns自动初始化它完毕后
使用navicat15,通过数据传输功能,可以迁移从mysql转义到海量数据库
**脚本转化过程中后,mysql中有默认值的设置,在pgsql脚本中没设置得手动设置**
## 数据库连接
使用navicat 创建pgsql的连接即可
![](.readme_images/236dbf98.png)
新建一个guns库
![](.readme_images/f653cfbf.png)
**将`海量数据库-sql初始化脚本.sql`执行并导入到这个库中**
## Guns程序适配
### 1.pom中用进入postgre sql驱动
```xml
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.5</version>
</dependency>
```
### 2.更改连接配置
**关闭`application.yml`中的flyway的配置开关,设置为**
```yml
spring:
flyway:
enabled: false
```
打开`application-local.yml`修改为海量数据库的连接配置
```yml
# 海量数据库配置
spring:
datasource:
driverClassName: org.postgresql.Driver
url: jdbc:postgresql://172.39.187.62:5432/test
username: vbadmin
password: T>685c1e
# 连接池大小根据实际情况调整
maxActive: 100
maxPoolPreparedStatementPerConnectionSize: 100
```
### 3.启动程序
启动GunsApplication即可
## 达梦数据库安装
下载地址:
链接:https://pan.baidu.com/s/1gKYiunnJjX5FQ2the0QMig?pwd=mlxz
提取码:mlxz
### 安装过程
安装过程参考安装目录下的手册,基本都是下一步下一步即可。
### 导入数据库
安装之后,使用DM管理工具打开数据库。
![](./.readme_images/bdb81f82.png)
账号密码都是SYSDBA
![](./.readme_images/60f185c8.png)
打开主界面,将db/dm_init.sql初始化脚本手动copy到dm管理工具中执行。
![](./.readme_images/c3b47f20.png)
执行成功后,可以看到初始化的表
![](./.readme_images/36a2ed96.png)
## 脚本适配注意事项
达梦脚本基本和oracle一致,但是主键不能和oracle一样用NUMBER(20,0),达梦中必须用bigint。
## Guns程序适配
### 1.pom中用进入达梦数据库驱动
```xml
<dependency>
<groupId>com.dameng</groupId>
<artifactId>Dm8JdbcDriver18</artifactId>
<version>8.1.1.49</version>
</dependency>
```
### 2.更改连接配置
打开application-local.yml,修改为oracle的相关配置
```yml
# 达梦数据库
spring:
datasource:
driverClassName: dm.jdbc.driver.DmDriver
url: jdbc:dm://172.39.187.62:5236?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&useSSL=true&characterEncoding=UTF-8
username: SYSDBA
password: SYSDBA
# 连接池大小根据实际情况调整
maxActive: 100
maxPoolPreparedStatementPerConnectionSize: 100
# 去掉wall的监控,只开启stat
filters: stat
```
flyway不支持达梦数据库,所以关掉flyway的配置,在application.yml中,设置flyway为false
```yml
spring:
flyway:
enabled: false
```
### 3.启动程序
# 代码混淆模块
代码混淆采用第三方工具allatori,官方网站:[http://www.allatori.com/](http://www.allatori.com/)
在本目录下有官网下载的Demo包(Allatori-8.1-Demo.zip),此包中包含了最全的代码混淆的用法讲解,例如:加密项目jar包,加密依赖jar包,pom加密插件配置等用法。
国内购买,可以找代理公司购买:[https://www.evget.com/product/3325/license](https://www.evget.com/product/3325/license)
## 加密过程
一般加密过程都是,准备好Jar包(项目jar或核心包的jar),在jar包同目录准备一个allatori的config.xml配置文件,使用如下命令进行jar包混淆操作。
```shell
java -Xms128m -Xmx512m -jar ..\..\..\lib\allatori.jar config.xml
```
之后,在同目录就会生成一个被混淆过的jar包,也就是混淆结果。目录结构如下:
![](.readme_images/2baab27e.png)
混淆前和混淆后对比如下,可以看到项目内部的变量名方法名等都已经被混淆为无法阅读的名称:
![](.readme_images/907cc9f6.png)
![](.readme_images/da6b8475.png)
## 具体操作步骤
### 1. 混淆jar包
准备好需要被混淆的jar包,以hutool核心包为例:
![](.readme_images/34fd824d.png)
在准备一个allatori的混淆文件,文件如下:
```xml
<config>
<input>
<!-- 被混淆的jar路径 -->
<jar in="hutool-all-5.7.16.jar" out="obf-hutool-all-5.7.16.jar"/>
</input>
<!-- protected和public类型 -->
<keep-names>
<class access="protected+">
<field access="protected+"/>
<method access="protected+"/>
</class>
</keep-names>
<!-- 混淆日志 -->
<property name="log-file" value="log.xml"/>
</config>
```
最后运行allatori的jar包,带上config.xml配置,即可进行混淆操作。
```shell
java -Xms128m -Xmx512m -jar ..\..\..\lib\allatori.jar config.xml
```
混淆结果如下:
![](.readme_images/11504a95.png)
混淆前后对比:
![](.readme_images/7c02c889.png)
![](.readme_images/fd30081a.png)
**allatori的所有配置,可以在allatori的官网找到:[http://www.allatori.com/doc.html](http://www.allatori.com/doc.html)**
### 2. 混淆Guns相关核心包
混淆Guns项目,或者Guns中的核心jar包,一般需要注意实体转化的问题,所有的pojo类型,不能被混淆,因为这些被混淆后,前端接收到的参数就变为a、b、c这种字段名了,还有mybatis和mybatis-plus相关的方法和xml的内容都不能混淆,混淆后mybatis不能识别。
下面是一个通用的Guns的混淆配置:
```xml
<config>
<!--首先指出要被混淆的jar包-->
<input>
<jar in="api-manager-api.jar" out="api-manager-api.jar"/>
</input>
<!--public方法不进行名称修改-->
<keep-names>
<class access="protected+">
<field access="protected+"/>
<method access="protected+"/>
</class>
<!--方法名称不混淆-->
<method template="*(**)" parameters="keep"/>
</keep-names>
<!--忽略进行混淆的类-->
<ignore-classes>
<class template="class *Application*"/>
<class template="class *springframework*"/>
<class template="class *alibaba*"/>
<class template="class *apache*"/>
<class template="class *model*"/>
<class template="class *pojo*"/>
<class template="class *entity*"/>
<class template="class *mapper*"/>
<class template="class *mapping*"/>
<class template="class *enums*"/>
</ignore-classes>
<!--本模块需要的class的路径,直接以maven仓库为路径,这里注意写你自己的就本地maven仓库路径-->
<classpath basedir="D:\repository">
<jar name="**/*.jar"/>
</classpath>
<!--混淆的日志-->
<property name="log-file" value="log.xml"/>
<!--资源文件使用utf8编码-->
<property name="update-resource-contents" value="disable"/>
<!--堆栈异常输出,obfuscate-混淆,remove-删除,keep-保留-->
<property name="line-numbers" value="keep"/>
</config>
```
混淆Guns的核心jar包之后的代码如下:
![](.readme_images/ab531f2e.png)
![](.readme_images/c2fdf605.png)
### 3. 混淆Guns项目
准备一个guns.jar的Guns后台项目,配置好配置后,
```xml
<config>
<input>
<jar in="guns.jar" out="obs-guns.jar"/>
</input>
<!--public方法不进行名称修改-->
<keep-names>
<class access="protected+">
<field access="protected+"/>
<method access="protected+"/>
</class>
<method template="*(**)" parameters="keep"/>
</keep-names>
<!--忽略进行混淆的类-->
<ignore-classes>
<class template="class *Application*"/>
<class template="class *springframework*"/>
<class template="class *alibaba*"/>
<class template="class *apache*"/>
<class template="class *model*"/>
<class template="class *pojo*"/>
<class template="class *entity*"/>
<class template="class *mapper*"/>
<class template="class *mapping*"/>
<class template="class *enums*"/>
</ignore-classes>
<!--本模块需要的class的路径,直接以maven仓库为路径-->
<classpath basedir="D:\repository">
<jar name="**/*.jar"/>
</classpath>
<!--混淆的日志-->
<property name="log-file" value="log.xml"/>
<!--资源文件使用utf8编码-->
<property name="update-resource-contents" value="disable"/>
<!--堆栈异常输出,obfuscate-混淆,remove-删除,keep-保留-->
<property name="line-numbers" value="keep"/>
</config>
```
执行如下命令,开始混淆:
![](.readme_images/e7c3b21c.png)
混淆成功,使用`java -jar obs-guns.jar`,可以正常访问系统
![](.readme_images/13cac7db.png)
![](.readme_images/05757008.png)
### 4. 混淆工具配置到maven插件
如果项目的发布,需要每次都混淆,可以将混淆功能集成到maven插件中,这样每次package之后,得到的就是混淆过的包,非常方便。
集成过程如下:
首先项目目录下建立一个allatori目录,里边放入allatori的jar包和xml配置。
配置如下:
```xml
<config>
<input>
<jar in="guns.jar" out="obs-guns.jar"/>
</input>
<!--public方法不进行名称修改-->
<keep-names>
<class access="protected+">
<field access="protected+"/>
<method access="protected+"/>
</class>
<method template="*(**)" parameters="keep"/>
</keep-names>
<!--忽略进行混淆的类-->
<ignore-classes>
<class template="class *Application*"/>
<class template="class *springframework*"/>
<class template="class *alibaba*"/>
<class template="class *apache*"/>
<class template="class *model*"/>
<class template="class *pojo*"/>
<class template="class *entity*"/>
<class template="class *mapper*"/>
<class template="class *mapping*"/>
<class template="class *enums*"/>
</ignore-classes>
<!--本模块需要的class的路径,直接以maven仓库为路径-->
<classpath basedir="D:\repository">
<jar name="**/*.jar"/>
</classpath>
<!--混淆的日志-->
<property name="log-file" value="log.xml"/>
<!--资源文件使用utf8编码-->
<property name="update-resource-contents" value="disable"/>
<!--堆栈异常输出,obfuscate-混淆,remove-删除,keep-保留-->
<property name="line-numbers" value="keep"/>
</config>
```
打开项目pom.xml,在plugins配置中,增加两个插件:
```xml
<plugins>
<!-- ...省略其他配置 -->
<!-- 将Allatori配置文件copy到target目录 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-and-filter-allatori-config</id>
<phase>package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<resources>
<resource>
<directory>${basedir}/allatori</directory>
<includes>
<include>allatori.xml</include>
</includes>
</resource>
</resources>
<outputDirectory>${basedir}/target</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!--执行Allatori混淆源码操作-->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>run-allatori</id>
<phase>package</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>java</executable>
<arguments>
<argument>-Xms512m</argument>
<argument>-Xmx512m</argument>
<argument>-jar</argument>
<argument>${basedir}/allatori/allatori.jar</argument>
<argument>${basedir}/target/allatori.xml</argument>
</arguments>
</configuration>
</plugin>
</plugins>
```
之后执行`mvn clean package`命令,即可为Guns项目打包,打包后可以看到混淆过后的jar包如下:
![](.readme_images/42135606.png)
# api授权
提供一个外部系统调用我方api的认证机制,对方首先通过api认证接口获取到token,然后携带token可以访问api客户端指定的接口
## 2023年8月19日11:55:38
用户管理和api鉴权管理需要区分开,单独写一个拦截器,或者在permission拦截器进行管理
\ No newline at end of file
# api模块,存放接口、常量、异常、枚举等模块规则相关类
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.javaguns.ent</groupId>
<artifactId>kernel-d-api-auth</artifactId>
<version>8.3.3</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>api-auth-api</artifactId>
<packaging>jar</packaging>
<dependencies>
<!--config模块的api-->
<dependency>
<groupId>com.javaguns.roses</groupId>
<artifactId>config-api</artifactId>
<version>${roses.version}</version>
</dependency>
<!--参数校验模块-->
<!--用在控制器,参数校验-->
<dependency>
<groupId>com.javaguns.roses</groupId>
<artifactId>validator-api</artifactId>
<version>${roses.version}</version>
</dependency>
</dependencies>
</project>
/*
* Copyright [2020-2030] [https://www.stylefeng.cn]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
*
* 1.请不要删除和修改根目录下的LICENSE文件。
* 2.请不要删除和修改Guns源码头部的版权声明。
* 3.请保留源码和相关描述文件的项目出处,作者声明等。
* 4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns
* 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns
* 6.若您的项目无法满足以上几点,可申请商业授权
*/
package cn.stylefeng.roses.kernel.apiauth.api;
/**
* api授权Api
*
* @author fengshuonan
* @date 2023-08-17 14:02:01
*/
public interface ApiAuthApi {
}
package cn.stylefeng.roses.kernel.apiauth.api;
/**
* api客户端的接口
*
* @author fengshuonan
* @date 2023/3/29 19:17
*/
public interface CaApiClientApi {
/**
* 获取ApiClient的名称
*
* @param caApiClientId 客户端id
* @return ApiClient的名称
* @author fengshuonan
* @date 2023/3/29 19:18
*/
String getCaApiClientName(Long caApiClientId);
}
/*
* Copyright [2020-2030] [https://www.stylefeng.cn]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
*
* 1.请不要删除和修改根目录下的LICENSE文件。
* 2.请不要删除和修改Guns源码头部的版权声明。
* 3.请保留源码和相关描述文件的项目出处,作者声明等。
* 4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns
* 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns
* 6.若您的项目无法满足以上几点,可申请商业授权
*/
package cn.stylefeng.roses.kernel.apiauth.api.annotations;
import java.lang.annotation.*;
/**
* 用来标记在方法上,进行API认证拦截
*
* @author fengshuonan
* @since 2023/10/26 14:11
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ApiAuth {
}
/*
* Copyright [2020-2030] [https://www.stylefeng.cn]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
*
* 1.请不要删除和修改根目录下的LICENSE文件。
* 2.请不要删除和修改Guns源码头部的版权声明。
* 3.请保留源码和相关描述文件的项目出处,作者声明等。
* 4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns
* 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns
* 6.若您的项目无法满足以上几点,可申请商业授权
*/
package cn.stylefeng.roses.kernel.apiauth.api.constants;
/**
* api授权业务
*
* @author fengshuonan
* @date 2023-08-17 14:02:01
*/
public interface ApiAuthConstants {
/**
* api授权模块名称
*/
String API_AUTH_MODULE_NAME = "kernel-s-api-auth";
/**
* 异常枚举的步进值
*/
String API_AUTH_EXCEPTION_STEP_CODE = "99";
/**
* Api认证的header名称
*/
String API_AUTH_HEADER_NAME = "ApiAuth";
/**
* payload中的clientId字段名称
*/
String API_AUTH_PAYLOAD_CLIENT_ID_FIELD_NAME = "apiClientId";
}
package cn.stylefeng.roses.kernel.apiauth.api.enums;
import lombok.Getter;
/**
* 一个示例
*
* @author fengshuonan
* @date 2023-08-17 14:02:01
*/
@Getter
public enum DemoEnum {
/**
* markdown格式
*/
MARKDOWN(1, "markdown格式"),
/**
* 富文本格式
*/
TEXT(2, "富文本格式");
private final Integer code;
private final String message;
DemoEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
}
/*
* Copyright [2020-2030] [https://www.stylefeng.cn]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
*
* 1.请不要删除和修改根目录下的LICENSE文件。
* 2.请不要删除和修改Guns源码头部的版权声明。
* 3.请保留源码和相关描述文件的项目出处,作者声明等。
* 4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns
* 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns
* 6.若您的项目无法满足以上几点,可申请商业授权
*/
package cn.stylefeng.roses.kernel.apiauth.api.exception;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.kernel.apiauth.api.constants.ApiAuthConstants;
import cn.stylefeng.roses.kernel.rule.exception.AbstractExceptionEnum;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
/**
* api授权异常
*
* @author fengshuonan
* @date 2023-08-17 14:02:01
*/
public class ApiAuthException extends ServiceException {
public ApiAuthException(AbstractExceptionEnum exception, Object... params) {
super(ApiAuthConstants.API_AUTH_MODULE_NAME, exception.getErrorCode(), StrUtil.format(exception.getUserTip(), params));
}
public ApiAuthException(AbstractExceptionEnum exception) {
super(ApiAuthConstants.API_AUTH_MODULE_NAME, exception);
}
}
/*
* Copyright [2020-2030] [https://www.stylefeng.cn]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
*
* 1.请不要删除和修改根目录下的LICENSE文件。
* 2.请不要删除和修改Guns源码头部的版权声明。
* 3.请保留源码和相关描述文件的项目出处,作者声明等。
* 4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns
* 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns
* 6.若您的项目无法满足以上几点,可申请商业授权
*/
package cn.stylefeng.roses.kernel.apiauth.api.exception.enums;
import cn.stylefeng.roses.kernel.apiauth.api.constants.ApiAuthConstants;
import cn.stylefeng.roses.kernel.rule.constants.RuleConstants;
import cn.stylefeng.roses.kernel.rule.exception.AbstractExceptionEnum;
import lombok.Getter;
/**
* api授权的异常枚举
*
* @author fengshuonan
* @date 2023-08-17 14:02:01
*/
@Getter
public enum ApiAuthExceptionEnum implements AbstractExceptionEnum {
/**
* 查询不到对应api授权
*/
CANT_FIND_API_AUTH(RuleConstants.BUSINESS_ERROR_TYPE_CODE + ApiAuthConstants.API_AUTH_EXCEPTION_STEP_CODE + "01", "查询不到对应api授权,具体信息:{}"),
/**
* API认证失败,请求Token格式错误
*/
API_AUTH_TOKEN_ERROR(RuleConstants.BUSINESS_ERROR_TYPE_CODE + ApiAuthConstants.API_AUTH_EXCEPTION_STEP_CODE + "02", "API认证失败,请求Token格式错误"),
/**
* API认证失败,token中的payload格式不对
*/
PAYLOAD_ERROR(RuleConstants.BUSINESS_ERROR_TYPE_CODE + ApiAuthConstants.API_AUTH_EXCEPTION_STEP_CODE + "03", "API认证失败,Token Payload格式错误"),
/**
* API认证失败,Token Client获取错误
*/
PAYLOAD_CLIENT_ID_CANT_GET(RuleConstants.BUSINESS_ERROR_TYPE_CODE + ApiAuthConstants.API_AUTH_EXCEPTION_STEP_CODE + "04", "API认证失败,Token Client获取错误"),
/**
* JWT Token错误
*/
JWT_TOKEN_ERROR(RuleConstants.BUSINESS_ERROR_TYPE_CODE + ApiAuthConstants.API_AUTH_EXCEPTION_STEP_CODE + "05", "API认证失败,JWT Token错误"),
/**
* API授权,权限异常,路径不合法
*/
URL_ERROR_RES_NOT_FOUND(RuleConstants.BUSINESS_ERROR_TYPE_CODE + ApiAuthConstants.API_AUTH_EXCEPTION_STEP_CODE + "06", "API授权,权限异常,路径不合法"),
/**
* API授权,权限异常,应用无权访问接口
*/
API_DONT_HAVE_AUTH(RuleConstants.BUSINESS_ERROR_TYPE_CODE + ApiAuthConstants.API_AUTH_EXCEPTION_STEP_CODE + "07", "API授权,权限异常,应用无权访问接口"),
/**
* API认证-请求token为空
*/
TOKEN_IS_EMPTY(RuleConstants.BUSINESS_ERROR_TYPE_CODE + ApiAuthConstants.API_AUTH_EXCEPTION_STEP_CODE + "08", "API认证-请求token为空"),
/**
* Token过期
*/
JWT_TOKEN_EXPIRED(RuleConstants.BUSINESS_ERROR_TYPE_CODE + ApiAuthConstants.API_AUTH_EXCEPTION_STEP_CODE + "09", "API认证失败,JWT Token过期");
/**
* 错误编码
*/
private final String errorCode;
/**
* 提示用户信息
*/
private final String userTip;
ApiAuthExceptionEnum(String errorCode, String userTip) {
this.errorCode = errorCode;
this.userTip = userTip;
}
}
package cn.stylefeng.roses.kernel.apiauth.api.format;
import cn.hutool.core.convert.Convert;
import cn.hutool.extra.spring.SpringUtil;
import cn.stylefeng.roses.kernel.apiauth.api.CaApiClientApi;
import cn.stylefeng.roses.kernel.rule.format.BaseSimpleFieldFormatProcess;
/**
* Json响应格式化,针对客户端id的渲染
*
* @author fengshuonan
* @date 2022/9/7 10:09
*/
public class CaApiClientProcess extends BaseSimpleFieldFormatProcess {
@Override
public Class<?> getItemClass() {
return Long.class;
}
@Override
public Object simpleItemFormat(Object businessId) {
CaApiClientApi caApiClientApi = SpringUtil.getBean(CaApiClientApi.class);
return caApiClientApi.getCaApiClientName(Convert.toLong(businessId));
}
}
# 业务模块-存放CRUD相关业务
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.javaguns.ent</groupId>
<artifactId>kernel-d-api-auth</artifactId>
<version>8.3.3</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>api-auth-business</artifactId>
<packaging>jar</packaging>
<dependencies>
<!--jwt工具-->
<dependency>
<groupId>com.javaguns.roses</groupId>
<artifactId>jwt-sdk</artifactId>
<version>${roses.version}</version>
</dependency>
<!--api授权api-->
<dependency>
<groupId>com.javaguns.ent</groupId>
<artifactId>api-auth-api</artifactId>
<version>${guns.ent.version}</version>
</dependency>
<!--system基础数据-->
<dependency>
<groupId>com.javaguns.roses</groupId>
<artifactId>system-spring-boot-starter</artifactId>
<version>${roses.version}</version>
</dependency>
<!--system业务api-->
<!--调用用户相关业务-->
<dependency>
<groupId>com.javaguns.roses</groupId>
<artifactId>system-api</artifactId>
<version>${roses.version}</version>
</dependency>
<!--资源api模块-->
<!--用在资源控制器,资源扫描上-->
<dependency>
<groupId>com.javaguns.roses</groupId>
<artifactId>scanner-api</artifactId>
<version>${roses.version}</version>
</dependency>
<!--数据库sdk-->
<!--数据库dao框架-->
<dependency>
<groupId>com.javaguns.roses</groupId>
<artifactId>db-sdk-mp</artifactId>
<version>${roses.version}</version>
</dependency>
<!--web模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--缓存的依赖-->
<!--sso的session可以用redis,可以用内存的-->
<dependency>
<groupId>com.javaguns.roses</groupId>
<artifactId>cache-api</artifactId>
<version>${roses.version}</version>
</dependency>
<dependency>
<groupId>com.javaguns.roses</groupId>
<artifactId>cache-sdk-memory</artifactId>
<version>${roses.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.javaguns.roses</groupId>
<artifactId>cache-sdk-redis</artifactId>
<version>${roses.version}</version>
<scope>provided</scope>
</dependency>
<!-- aop -->
<!-- 用于本模块api认证拦截 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
</project>
/*
* Copyright [2020-2030] [https://www.stylefeng.cn]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
*
* 1.请不要删除和修改根目录下的LICENSE文件。
* 2.请不要删除和修改Guns源码头部的版权声明。
* 3.请保留源码和相关描述文件的项目出处,作者声明等。
* 4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns
* 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns
* 6.若您的项目无法满足以上几点,可申请商业授权
*/
package cn.stylefeng.roses.kernel.auth.aop;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.kernel.apiauth.api.constants.ApiAuthConstants;
import cn.stylefeng.roses.kernel.apiauth.api.exception.enums.ApiAuthExceptionEnum;
import cn.stylefeng.roses.kernel.jwt.JwtTokenOperator;
import cn.stylefeng.roses.kernel.jwt.api.pojo.config.JwtConfig;
import cn.stylefeng.roses.kernel.manage.service.ApiClientAuthService;
import cn.stylefeng.roses.kernel.manage.service.ApiClientService;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;
import cn.stylefeng.roses.kernel.scanner.api.pojo.resource.ResourceDefinition;
import cn.stylefeng.roses.kernel.scanner.api.pojo.resource.ResourceUrlParam;
import cn.stylefeng.roses.kernel.sys.api.ResourceServiceApi;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
/**
* API认证的AOP拦截
*
* @author fengshuonan
* @since 2023/10/26 14:18
*/
@Aspect
@Slf4j
public class ApiAuthAop {
@Resource
private ApiClientService apiClientService;
@Resource
private ResourceServiceApi resourceServiceApi;
@Resource
private ApiClientAuthService apiClientAuthService;
/**
* 针对注解进行切面逻辑执行
*
* @author fengshuonan
* @since 2023/10/26 14:18
*/
@Pointcut(value = "@annotation(cn.stylefeng.roses.kernel.apiauth.api.annotations.ApiAuth)")
public void cutService() {
}
@Around("cutService()")
public Object aroundPost(ProceedingJoinPoint joinPoint) throws Throwable {
// 执行权限校验
this.authExecute(joinPoint);
// 执行真正业务逻辑
return joinPoint.proceed();
}
private void authExecute(ProceedingJoinPoint joinPoint) {
// 1. 获取当前Http请求的信息
HttpServletRequest request = HttpServletUtil.getRequest();
// 2. 获取当前请求的路径,过滤掉多个/的问题
String requestURI = request.getRequestURI();
requestURI = requestURI.replaceAll("/+", "/");
// 3. 获取当前API客户端的Token值,可能为null,读取Header中的值
String token = request.getHeader(ApiAuthConstants.API_AUTH_HEADER_NAME);
if (StrUtil.isEmpty(token)) {
throw new ServiceException(ApiAuthExceptionEnum.TOKEN_IS_EMPTY);
}
// 4. 获取token是否为正常的JWT格式(带两个英文点)
String[] split = token.split("\\.");
if (split.length != 3) {
throw new ServiceException(ApiAuthExceptionEnum.API_AUTH_TOKEN_ERROR);
}
// 5. 获取token的payload部分
String payloadString = split[1];
// base64解码,获取客户端id
String payloadJson = Base64.decodeStr(payloadString);
JSONObject payloadObject = null;
try {
payloadObject = JSON.parseObject(payloadJson);
} catch (Exception e) {
throw new ServiceException(ApiAuthExceptionEnum.API_AUTH_TOKEN_ERROR);
}
// 获取payload中的clientId
Long clientId = payloadObject.getLong(ApiAuthConstants.API_AUTH_PAYLOAD_CLIENT_ID_FIELD_NAME);
if (clientId == null) {
throw new ServiceException(ApiAuthExceptionEnum.PAYLOAD_CLIENT_ID_CANT_GET);
}
// 获取客户端秘钥
String apiClientSecret = apiClientService.getApiClientSecret(clientId);
if (ObjectUtil.isEmpty(apiClientSecret)) {
throw new ServiceException(ApiAuthExceptionEnum.PAYLOAD_CLIENT_ID_CANT_GET);
}
// 先校验token是否过期
JwtConfig jwtConfig = new JwtConfig();
jwtConfig.setJwtSecret(apiClientSecret);
JwtTokenOperator jwtTokenOperator = new JwtTokenOperator(jwtConfig);
boolean expiredFlag = jwtTokenOperator.validateTokenIsExpired(token);
if (expiredFlag) {
throw new ServiceException(ApiAuthExceptionEnum.JWT_TOKEN_EXPIRED);
}
// 校验token是否正确
boolean tokenRight = jwtTokenOperator.validateToken(token);
if (!tokenRight) {
throw new ServiceException(ApiAuthExceptionEnum.JWT_TOKEN_ERROR);
}
// 获取ResourceDefinition,可能为null
ResourceUrlParam resourceUrlParam = new ResourceUrlParam();
resourceUrlParam.setUrl(requestURI);
ResourceDefinition resourceDefinition = resourceServiceApi.getResourceByUrl(resourceUrlParam);
if (resourceDefinition == null) {
throw new ServiceException(ApiAuthExceptionEnum.URL_ERROR_RES_NOT_FOUND);
}
// 获取资源的code编码
String resourceCode = resourceDefinition.getResourceCode();
// 获取当前客户端,是否有访问该资源的权限
boolean clientAuthRight = apiClientAuthService.validateClientAuth(clientId, resourceCode);
if (!clientAuthRight) {
throw new ServiceException(ApiAuthExceptionEnum.API_DONT_HAVE_AUTH);
}
}
}
package cn.stylefeng.roses.kernel.auth.controller;
import cn.stylefeng.roses.kernel.apiauth.api.annotations.ApiAuth;
import cn.stylefeng.roses.kernel.auth.pojo.AuthTokenRequest;
import cn.stylefeng.roses.kernel.auth.pojo.AuthTokenResponse;
import cn.stylefeng.roses.kernel.auth.service.AuthTokenService;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.kernel.scanner.api.annotation.ApiResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.GetResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.PostResource;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RestController;
/**
* 接入认证的控制器
*
* @author fengshuonan
* @since 2023/10/25 22:14
*/
@RestController
@ApiResource(name = "接入认证的控制器")
public class ConnectController {
@Resource
private AuthTokenService authTokenService;
/**
* api客户端接入-获取token
*
* @author fengshuonan
* @since 2023/10/25 22:14
*/
@GetResource(name = "api客户端接入-获取token", path = "/apiAuth/generateAuthToken", requiredLogin = false)
public ResponseData<AuthTokenResponse> generateAuthToken(AuthTokenRequest authTokenRequest) {
return new SuccessResponseData<>(authTokenService.generateAuthToken(authTokenRequest));
}
/**
* 测试API认证访问的接口,如果成功会返回一个success
*
* @author fengshuonan
* @since 2023/10/26 16:09
*/
@PostResource(name = "测试API认证访问的接口", path = "/apiAuth/test", requiredLogin = false)
@ApiAuth
public ResponseData<String> test() {
return new SuccessResponseData<>("test success");
}
}
package cn.stylefeng.roses.kernel.auth.exception;
import cn.stylefeng.roses.kernel.rule.constants.RuleConstants;
import cn.stylefeng.roses.kernel.rule.exception.AbstractExceptionEnum;
import lombok.Getter;
/**
* API客户端异常相关枚举
*
* @author fengshuonan
* @date 2022/03/23 14:02
*/
@Getter
public enum ApiClientExceptionEnum implements AbstractExceptionEnum {
/**
* API认证请求时间过期,请从新认证
*/
API_CLIENT_AUTH_EXPIRED(RuleConstants.BUSINESS_ERROR_TYPE_CODE + "11002", "API登录请求时间过期,请从新调用认证接口"),
/**
* API登录失败,秘钥不正确
*/
API_CLIENT_LOGIN_SECRET_ERROR(RuleConstants.BUSINESS_ERROR_TYPE_CODE + "11004", "API登录失败,秘钥不正确"),
/**
* API登录失败,API客户端被禁用
*/
API_CLIENT_DISABLED(RuleConstants.BUSINESS_ERROR_TYPE_CODE + "11005", "API登录失败,API客户端被禁用"),
/**
* 时间戳格式不对
*/
TIMESTAMP_ERROR(RuleConstants.BUSINESS_ERROR_TYPE_CODE + "11006", "API登录失败,时间戳格式不对");
/**
* 错误编码
*/
private final String errorCode;
/**
* 提示用户信息
*/
private final String userTip;
ApiClientExceptionEnum(String errorCode, String userTip) {
this.errorCode = errorCode;
this.userTip = userTip;
}
}
package cn.stylefeng.roses.kernel.auth.pojo;
import cn.stylefeng.roses.kernel.rule.annotation.ChineseDescription;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* 获取api认证token的请求参数
*
* @author fengshuonan
* @since 2023/10/25 22:25
*/
@Data
public class AuthTokenRequest {
/**
* API客户端唯一标识
* <p>
* 对应api_client表的code
*/
@ChineseDescription("API客户端唯一标识")
@NotBlank(message = "API客户端唯一标识不能为空")
private String apiClientCode;
/**
* API客户端认证秘钥编码
* <p>
* 具体加密过程:md5(秘钥 + 时间戳(例如:202203231123))
*/
@ChineseDescription("API客户端认证秘钥编码")
@NotBlank(message = "API客户端认证秘钥编码不能为空")
private String apiClientSecretEncode;
/**
* 请求时候的时间戳,精确到秒(例如:202203231123)
*/
@ChineseDescription("时间戳")
@NotBlank(message = "时间戳不能为空")
private String timestamp;
}
package cn.stylefeng.roses.kernel.auth.pojo;
import cn.stylefeng.roses.kernel.rule.annotation.ChineseDescription;
import lombok.Data;
/**
* 认证token响应结果
*
* @author fengshuonan
* @since 2023/10/25 22:21
*/
@Data
public class AuthTokenResponse {
/**
* 客户端token
*/
@ChineseDescription("客户端token")
private String token;
}
package cn.stylefeng.roses.kernel.auth.service;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.stylefeng.roses.kernel.apiauth.api.constants.ApiAuthConstants;
import cn.stylefeng.roses.kernel.auth.exception.ApiClientExceptionEnum;
import cn.stylefeng.roses.kernel.auth.pojo.AuthTokenRequest;
import cn.stylefeng.roses.kernel.auth.pojo.AuthTokenResponse;
import cn.stylefeng.roses.kernel.jwt.JwtTokenOperator;
import cn.stylefeng.roses.kernel.jwt.api.pojo.config.JwtConfig;
import cn.stylefeng.roses.kernel.manage.entity.ApiClient;
import cn.stylefeng.roses.kernel.manage.service.ApiClientService;
import cn.stylefeng.roses.kernel.rule.enums.StatusEnum;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
/**
* 创建api认证的token
*
* @author fengshuonan
* @since 2023/10/25 22:21
*/
@Service
public class AuthTokenService {
@Resource
private ApiClientService apiClientService;
/**
* 获取认证token
*
* @author fengshuonan
* @since 2023/10/25 22:25
*/
public AuthTokenResponse generateAuthToken(AuthTokenRequest authTokenRequest) {
// 1. 时间戳转化为日期格式
String timestamp = authTokenRequest.getTimestamp();
DateTime requestDateTime = null;
try {
requestDateTime = DateUtil.parse(timestamp);
} catch (Exception e) {
throw new ServiceException(ApiClientExceptionEnum.TIMESTAMP_ERROR);
}
// 2. 判断时间是否过期,过期则直接认证失败,2分钟时间过期
DateTime expiredDateTime = requestDateTime.offset(DateField.MINUTE, 2);
if (expiredDateTime.isBefore(new Date())) {
throw new ServiceException(ApiClientExceptionEnum.API_CLIENT_AUTH_EXPIRED);
}
// 3. 根据api客户端编码,查询到这个api客户端信息
String apiClientCode = authTokenRequest.getApiClientCode();
ApiClient apiClient = apiClientService.getByCode(apiClientCode);
// 3.1 校验客户端是否被禁用
if (!apiClient.getApiClientStatus().equals(StatusEnum.ENABLE.getCode())) {
throw new ServiceException(ApiClientExceptionEnum.API_CLIENT_DISABLED);
}
// 4. 获取md5加密的字符串(客户端秘钥+时间戳)
String secretWithTimestampMd5 = authTokenRequest.getApiClientSecretEncode();
// 5. 将客户端本身的秘钥和时间戳加密得出正确的md5值,并进行比对
String rightMd5 = SecureUtil.md5(apiClient.getApiClientSecret() + authTokenRequest.getTimestamp());
if (!rightMd5.equals(secretWithTimestampMd5)) {
throw new ServiceException(ApiClientExceptionEnum.API_CLIENT_LOGIN_SECRET_ERROR);
}
// 6. 如果校验通过,颁发Token
AuthTokenResponse authTokenResponse = new AuthTokenResponse();
// 获取jwt秘钥信息和token过期时间
JwtConfig jwtConfig = new JwtConfig();
jwtConfig.setJwtSecret(apiClient.getApiClientSecret());
jwtConfig.setExpiredSeconds(Convert.toLong(apiClient.getApiClientTokenExpiration()));
JwtTokenOperator jwtTokenOperator = new JwtTokenOperator(jwtConfig);
// 组装payload
HashMap<String, Object> payload = new HashMap<>();
payload.put(ApiAuthConstants.API_AUTH_PAYLOAD_CLIENT_ID_FIELD_NAME, apiClient.getApiClientId());
// 生成token
String token = jwtTokenOperator.generateToken(payload);
authTokenResponse.setToken(token);
return authTokenResponse;
}
}
package cn.stylefeng.roses.kernel.auth.test;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.stylefeng.roses.kernel.auth.pojo.AuthTokenRequest;
import java.util.Date;
/**
* 生成token的测试类
*
* @author fengshuonan
* @since 2023/10/26 11:20
*/
public class TokenGenerateExample {
public static void main(String[] args) {
// 获取用户的秘钥
String secret = "cufqwoo9ar843gxj";
System.out.println(secret);
AuthTokenRequest authTokenRequest = new AuthTokenRequest();
// 创建时间戳
authTokenRequest.setTimestamp(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
// 生成签名
authTokenRequest.setApiClientSecretEncode(SecureUtil.md5(secret + authTokenRequest.getTimestamp()));
// 设置客户端编码
authTokenRequest.setApiClientCode("jd");
System.out.println(authTokenRequest);
}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown 格式
0% or
您添加了 0 人 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册 或