From 12a55506888254a2e5b62c240096dd3c2103916e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AD=99=E5=B0=8F=E4=BA=91?= Date: Fri, 18 Jul 2025 14:28:47 +0800 Subject: [PATCH] first --- database.md | 119 ++++++++ gateway/.DS_Store | Bin 0 -> 6148 bytes gateway/.idea/compiler.xml | 18 ++ gateway/.idea/encodings.xml | 6 + gateway/.idea/jarRepositories.xml | 30 ++ gateway/.idea/misc.xml | 12 + gateway/.idea/vcs.xml | 7 + gateway/.idea/workspace.xml | 115 +++++++ gateway/pom.xml | 67 ++++ .../tuoheng/gateway/GatewayApplication.java | 11 + .../gateway/config/SecurityConfig.java | 22 ++ .../src/main/resources/application.properties | 14 + gateway/target/classes/application.properties | 14 + .../tuoheng/gateway/GatewayApplication.class | Bin 0 -> 748 bytes .../gateway/config/SecurityConfig.class | Bin 0 -> 3458 bytes nginx/nginx.conf | 193 ++++++++++++ oauth2.md | 51 ++++ oidc.md | 14 + oidc/.gitattributes | 2 + oidc/.gitignore | 33 ++ oidc/.mvn/wrapper/maven-wrapper.properties | 19 ++ oidc/mvnw | 259 ++++++++++++++++ oidc/mvnw.cmd | 149 +++++++++ oidc/pom.xml | 72 +++++ .../tuoheng/oauth/oidc/OidcApplication.java | 13 + .../oauth/oidc/config/SecurityConfig.java | 184 +++++++++++ .../oidc/controller/ResourceController.java | 19 ++ .../src/main/resources/application.properties | 4 + .../oauth/oidc/OidcApplicationTests.java | 13 + request.md | 22 ++ resourceservice/.idea/.gitignore | 8 + resourceservice/.idea/compiler.xml | 18 ++ resourceservice/.idea/encodings.xml | 6 + resourceservice/.idea/jarRepositories.xml | 30 ++ resourceservice/.idea/misc.xml | 12 + resourceservice/.idea/vcs.xml | 6 + resourceservice/pom.xml | 38 +++ .../resourceservice/HelloController.java | 18 ++ .../ResourceServiceApplication.java | 11 + .../src/main/resources/application.properties | 1 + .../target/classes/application.properties | 1 + .../resourceservice/HelloController.class | Bin 0 -> 1223 bytes .../ResourceServiceApplication.class | Bin 0 -> 788 bytes resourceservicehtml/callback.html | 204 +++++++++++++ resourceservicehtml/index.html | 286 ++++++++++++++++++ resourceservicehtml/test.html | 202 +++++++++++++ ssl/certificate.crt | 23 ++ ssl/private.key | 28 ++ 48 files changed, 2374 insertions(+) create mode 100644 database.md create mode 100644 gateway/.DS_Store create mode 100644 gateway/.idea/compiler.xml create mode 100644 gateway/.idea/encodings.xml create mode 100644 gateway/.idea/jarRepositories.xml create mode 100644 gateway/.idea/misc.xml create mode 100644 gateway/.idea/vcs.xml create mode 100644 gateway/.idea/workspace.xml create mode 100644 gateway/pom.xml create mode 100644 gateway/src/main/java/com/tuoheng/gateway/GatewayApplication.java create mode 100644 gateway/src/main/java/com/tuoheng/gateway/config/SecurityConfig.java create mode 100644 gateway/src/main/resources/application.properties create mode 100644 gateway/target/classes/application.properties create mode 100644 gateway/target/classes/com/tuoheng/gateway/GatewayApplication.class create mode 100644 gateway/target/classes/com/tuoheng/gateway/config/SecurityConfig.class create mode 100644 nginx/nginx.conf create mode 100644 oauth2.md create mode 100644 oidc.md create mode 100644 oidc/.gitattributes create mode 100644 oidc/.gitignore create mode 100644 oidc/.mvn/wrapper/maven-wrapper.properties create mode 100755 oidc/mvnw create mode 100644 oidc/mvnw.cmd create mode 100644 oidc/pom.xml create mode 100644 oidc/src/main/java/com/tuoheng/oauth/oidc/OidcApplication.java create mode 100644 oidc/src/main/java/com/tuoheng/oauth/oidc/config/SecurityConfig.java create mode 100644 oidc/src/main/java/com/tuoheng/oauth/oidc/controller/ResourceController.java create mode 100644 oidc/src/main/resources/application.properties create mode 100644 oidc/src/test/java/com/tuoheng/oauth/oidc/OidcApplicationTests.java create mode 100644 request.md create mode 100644 resourceservice/.idea/.gitignore create mode 100644 resourceservice/.idea/compiler.xml create mode 100644 resourceservice/.idea/encodings.xml create mode 100644 resourceservice/.idea/jarRepositories.xml create mode 100644 resourceservice/.idea/misc.xml create mode 100644 resourceservice/.idea/vcs.xml create mode 100644 resourceservice/pom.xml create mode 100644 resourceservice/src/main/java/com/tuoheng/resourceservice/HelloController.java create mode 100644 resourceservice/src/main/java/com/tuoheng/resourceservice/ResourceServiceApplication.java create mode 100644 resourceservice/src/main/resources/application.properties create mode 100644 resourceservice/target/classes/application.properties create mode 100644 resourceservice/target/classes/com/tuoheng/resourceservice/HelloController.class create mode 100644 resourceservice/target/classes/com/tuoheng/resourceservice/ResourceServiceApplication.class create mode 100644 resourceservicehtml/callback.html create mode 100644 resourceservicehtml/index.html create mode 100644 resourceservicehtml/test.html create mode 100644 ssl/certificate.crt create mode 100644 ssl/private.key diff --git a/database.md b/database.md new file mode 100644 index 0000000..5de1a7d --- /dev/null +++ b/database.md @@ -0,0 +1,119 @@ +# 数据库表结构设计 + +## 一、统一认证网关(主工程)表结构 + +### 1. 用户表(users) +| 字段名 | 类型 | 说明 | +| -------------- | -------------- | -------------------------- | +| id | BIGINT | 主键,自增 | +| username | VARCHAR(50) | 用户名(租户/子系统内唯一)| +| password | VARCHAR(255) | 密码(加密存储) | +| user_type | ENUM | 用户类型(TENANT/SUBSYSTEM)| +| tenant_id | BIGINT | 所属租户ID,外键->tenants.id(所有用户必填,标识归属租户) | +| subsystem_id | BIGINT | 所属子系统ID,外键->subsystems.id(仅子系统用户必填)| +| email | VARCHAR(100) | 邮箱 | +| phone | VARCHAR(20) | 手机号 | +| real_name | VARCHAR(50) | 真实姓名 | +| status | ENUM | 状态(ACTIVE/INACTIVE/LOCKED/DELETED)| +| create_time | TIMESTAMP | 创建时间 | +| update_time | TIMESTAMP | 更新时间 | +| UNIQUE KEY uk_tenant_username (tenant_id, username) | +| UNIQUE KEY uk_subsystem_username (subsystem_id, username) | + +> 主键:id +> 外键:tenant_id 关联 tenants.id(所有用户必填),subsystem_id 关联 subsystems.id(仅子系统用户必填) + +### 2. 租户表(tenants) +| 字段名 | 类型 | 说明 | +| -------------- | -------------- | -------------------------- | +| id | BIGINT | 主键,自增 | +| tenant_code | VARCHAR(50) | 租户唯一标识 | +| tenant_name | VARCHAR(100) | 租户名称 | +| description | TEXT | 描述 | +| status | ENUM | 状态(ACTIVE/INACTIVE) | +| create_time | TIMESTAMP | 创建时间 | +| update_time | TIMESTAMP | 更新时间 | + +> 主键:id + +### 3. 子系统表(subsystems) +| 字段名 | 类型 | 说明 | +| -------------- | -------------- | -------------------------- | +| id | BIGINT | 主键,自增 | +| subsystem_code | VARCHAR(50) | 子系统唯一标识 | +| subsystem_name | VARCHAR(100) | 子系统名称 | +| description | TEXT | 描述 | +| base_url | VARCHAR(255) | 子系统入口地址 | +| status | ENUM | 状态(ACTIVE/INACTIVE) | +| create_time | TIMESTAMP | 创建时间 | +| update_time | TIMESTAMP | 更新时间 | + +> 主键:id + +### 4. 租户-子系统权限表(tenant_subsystem_permissions) +| 字段名 | 类型 | 说明 | +| -------------- | -------------- | -------------------------- | +| id | BIGINT | 主键,自增 | +| tenant_id | BIGINT | 租户ID,外键->tenants.id | +| subsystem_id | BIGINT | 子系统ID,外键->subsystems.id | +| permissions | JSON | 权限配置 | +| status | ENUM | 状态(ACTIVE/INACTIVE) | +| create_time | TIMESTAMP | 创建时间 | +| update_time | TIMESTAMP | 更新时间 | +| UNIQUE KEY uk_tenant_subsystem (tenant_id, subsystem_id) | + +> 主键:id +> 外键:tenant_id 关联 tenants.id,subsystem_id 关联 subsystems.id + + +## 二、子系统(如订单、支付等)表结构 + +### 1. 业务用户表(users 和 统一认证网关(主工程) 用的不是一个数据库,表名可以重复) +| 字段名 | 类型 | 说明 | +| -------------- | -------------- | -------------------------- | +| id | BIGINT | 主键,自增 | +| user_id | BIGINT | 关联统一认证网关 users 表的 id 字段,外键->users.id | +| username | VARCHAR(50) | 业务系统内用户名 | +| ... | ... | 业务相关字段(如地址、类型等)| +| create_time | TIMESTAMP | 创建时间 | +| update_time | TIMESTAMP | 更新时间 | + +> 主键:id +> 外键:user_id 关联统一认证网关 users.id(users 表为统一认证主工程的用户表) + +--- + +**主外键关系说明:** +- users.tenant_id → tenants.id +- users.subsystem_id → subsystems.id +- tenant_subsystem_permissions.tenant_id → tenants.id +- tenant_subsystem_permissions.subsystem_id → subsystems.id +- 子系统业务用户表 user_id → 统一认证 users.id +- 业务数据表 user_id → 统一认证 users.id + + +-- 插入租户 +INSERT INTO tenants (id, tenant_code, tenant_name, description, status, create_time, update_time) +VALUES (1, 'test-tenant', '测试租户', '测试用租户', 'ACTIVE', NOW(), NOW()); + +-- 插入用户 +INSERT INTO users ( + id, username, password, user_type, tenant_id, subsystem_id, email, phone, real_name, status, create_time, update_time +) VALUES ( + 1, + 'testuser', + '$2a$10$wH6Qw6Qw6Qw6Qw6Qw6Qw6uQw6Qw6Qw6Qw6Qw6Qw6Qw6Qw6Qw6Qw6', -- 密码123456的BCrypt加密 + 'TENANT', + 1, + NULL, + 'testuser@example.com', + '13800000000', + '测试用户', + 'ACTIVE', + NOW(), + NOW() +); + +租户ID:1 或 租户名:test-tenant +用户名:testuser +密码:123456 diff --git a/gateway/.DS_Store b/gateway/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..527f523c99c258a1846f14fe6337fa89476d47d9 GIT binary patch literal 6148 zcmeHKJE{Uf5bSmh1d|O7=LCW`7(@eOFCc0t2tLd=@?7s)FVgA{qO2wlOr#pRYo@1b zm#tuXT10ey-p@o@5gEY^h_Ar92KAfRDcRl0V?n>1+4eNM&m$6DnJFOz+D0RKNPrOP3!{w*MZ<80C0%3 z8`ggL2Np{JYho9O3`~Ox465dcp*cHf&~aX~z6%VxsJ|J{$v10GD4L^(7B3gAfs9mu z3Op;&#J08mzl6V;|DQ?RQ2{FORSM{Ev0lvaN!eR_A7{O`z&CKK`GuQd?GyxW$3Sn# g*jPKBcu~|9TjRVYc7aYu-swPI222+k75KCQH$)j3vH$=8 literal 0 HcmV?d00001 diff --git a/gateway/.idea/compiler.xml b/gateway/.idea/compiler.xml new file mode 100644 index 0000000..aa5b26f --- /dev/null +++ b/gateway/.idea/compiler.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/gateway/.idea/encodings.xml b/gateway/.idea/encodings.xml new file mode 100644 index 0000000..63e9001 --- /dev/null +++ b/gateway/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/gateway/.idea/jarRepositories.xml b/gateway/.idea/jarRepositories.xml new file mode 100644 index 0000000..bef82d8 --- /dev/null +++ b/gateway/.idea/jarRepositories.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/gateway/.idea/misc.xml b/gateway/.idea/misc.xml new file mode 100644 index 0000000..4b8acaf --- /dev/null +++ b/gateway/.idea/misc.xml @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/gateway/.idea/vcs.xml b/gateway/.idea/vcs.xml new file mode 100644 index 0000000..288b36b --- /dev/null +++ b/gateway/.idea/vcs.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/gateway/.idea/workspace.xml b/gateway/.idea/workspace.xml new file mode 100644 index 0000000..27d6df4 --- /dev/null +++ b/gateway/.idea/workspace.xml @@ -0,0 +1,115 @@ + + + + + + + + + + + + + + + + + + + + { + "associatedIndex": 1 +} + + + + + + + + + + + + + + + + + + + + + 1733367147290 + + + + + + \ No newline at end of file diff --git a/gateway/pom.xml b/gateway/pom.xml new file mode 100644 index 0000000..de0cc33 --- /dev/null +++ b/gateway/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.18 + + + com.tuoheng + gateway + 0.0.1-SNAPSHOT + gateway + Spring Boot 2.7.x Servlet Gateway + + 11 + 2021.0.8 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework.cloud + spring-cloud-starter-gateway + + + + org.springframework.boot + spring-boot-starter-oauth2-resource-server + + + + org.springframework.boot + spring-boot-starter-oauth2-client + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/gateway/src/main/java/com/tuoheng/gateway/GatewayApplication.java b/gateway/src/main/java/com/tuoheng/gateway/GatewayApplication.java new file mode 100644 index 0000000..fb7ce6b --- /dev/null +++ b/gateway/src/main/java/com/tuoheng/gateway/GatewayApplication.java @@ -0,0 +1,11 @@ +package com.tuoheng.gateway; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class GatewayApplication { + public static void main(String[] args) { + SpringApplication.run(GatewayApplication.class, args); + } +} \ No newline at end of file diff --git a/gateway/src/main/java/com/tuoheng/gateway/config/SecurityConfig.java b/gateway/src/main/java/com/tuoheng/gateway/config/SecurityConfig.java new file mode 100644 index 0000000..8dc168f --- /dev/null +++ b/gateway/src/main/java/com/tuoheng/gateway/config/SecurityConfig.java @@ -0,0 +1,22 @@ +package com.tuoheng.gateway.config; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; + +@Configuration +@EnableWebFluxSecurity +public class SecurityConfig { + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(exchanges -> exchanges + .pathMatchers("/test/**").permitAll() // 测试路径不需要认证 + .pathMatchers("/api/**").authenticated() + .anyExchange().permitAll() + ) + .oauth2ResourceServer(oauth2 -> oauth2.jwt()); + return http.build(); + } +} \ No newline at end of file diff --git a/gateway/src/main/resources/application.properties b/gateway/src/main/resources/application.properties new file mode 100644 index 0000000..62cdc6a --- /dev/null +++ b/gateway/src/main/resources/application.properties @@ -0,0 +1,14 @@ +server.port=8080 + +spring.cloud.gateway.routes[0].id=resource-server +spring.cloud.gateway.routes[0].uri=http://localhost:8081 +spring.cloud.gateway.routes[0].predicates[0]=Path=/api/** +spring.cloud.gateway.routes[0].filters[0]=TokenRelay + +# 添加一个不需要认证的测试路由 +spring.cloud.gateway.routes[1].id=test-route +spring.cloud.gateway.routes[1].uri=http://localhost:8081 +spring.cloud.gateway.routes[1].predicates[0]=Path=/test/** +spring.cloud.gateway.routes[1].filters[0]=RewritePath=/test/(?.*), /api/$\{segment} + +spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:9000/oauth2/jwks \ No newline at end of file diff --git a/gateway/target/classes/application.properties b/gateway/target/classes/application.properties new file mode 100644 index 0000000..62cdc6a --- /dev/null +++ b/gateway/target/classes/application.properties @@ -0,0 +1,14 @@ +server.port=8080 + +spring.cloud.gateway.routes[0].id=resource-server +spring.cloud.gateway.routes[0].uri=http://localhost:8081 +spring.cloud.gateway.routes[0].predicates[0]=Path=/api/** +spring.cloud.gateway.routes[0].filters[0]=TokenRelay + +# 添加一个不需要认证的测试路由 +spring.cloud.gateway.routes[1].id=test-route +spring.cloud.gateway.routes[1].uri=http://localhost:8081 +spring.cloud.gateway.routes[1].predicates[0]=Path=/test/** +spring.cloud.gateway.routes[1].filters[0]=RewritePath=/test/(?.*), /api/$\{segment} + +spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:9000/oauth2/jwks \ No newline at end of file diff --git a/gateway/target/classes/com/tuoheng/gateway/GatewayApplication.class b/gateway/target/classes/com/tuoheng/gateway/GatewayApplication.class new file mode 100644 index 0000000000000000000000000000000000000000..0e4fc1f970846a280ba821c5de9cb097ce7c3213 GIT binary patch literal 748 zcma)4O;6iE5PcgG986juP$;wurE1g%*aImGwIwA|_i1%o6lFhCVAL9~tKW(r8Km5boXpV6^C2(wUdO9j@cegs$3wz+`d9fbs&zf*9h0 zDqpu9t^7h&+OEJa*`nt!nL*vR-K9le*3_Ekub3_ImW6Ao%sqcq`7|~hZfad`nVrwQ zUPssA$Wz@g2ypyOH5!f!FXY6~#FeIA!28J`flvH*BXO zF!Lr)c3r$pz!OzwkU*hlZ2w#OvD)Soy;`{^!vtn>Giin#Su0m$=Ayupo%y#5^;UOf zrnkneR999$H=o2rSGAXPSV==TM+l}?fi@>5Qn-MNNtgl)yUwHDKnz^MWdWlub#+c^ ztJ?Iz+3e$Dn};G~EY|i`L{0f5J`#AkPtY>cmZgFqg(+MyNT;8&EbGdz*?QV>1RlRB znc}kiKhYV&=K@Jn*6n5xrf}837a@RyVWuk*jzuD`gyH$pz*m?SI3V4Pc4e0L4_xdP zQs1zOnSfdQaQEfVJ3)9)t0FE5Jll(kxEq$l7P^RwB83~cmBdYfN4w9e?d~yf8{e>- zF0ZkbfA4%kJy+c z{{ZC2?*vY_DaUqKy%l8^o9s+Mxk$C1zhPhj-?RS6->ofyzq1`=6`zch-;{2}Q9-8Y zc`J>2zC$dgxsIK#gAX?9s#ARDe@0in{%j|?#+nP#aZ0vU`H?}C1deu^6!ULxK8;5y z_TwK6oJE#`PtwT7du0P(W0rd|jagFsE!XAi&5=Q%f+Us%&b;E>UM@<)7C8BOQD%4K zPr~fk?OA2dt8+`Mc4K7*#{&z<71lNBv&R!!Es>XIfj1Y zqz@^6!@t4V0e+20fa5`~1P)<@s?xF4VUD4q1)l8Vczp5&_`cl4u@`tJ9N%4-+{F98 z@~=qsC=r0FLPf(EqwtaDHOHdk@ikP049-yMLrM<_E|5-zq32e3UztXP7|%^4en;+M z|LA0C6X*ZL)FwWTcRqW$li$QO?zioWKpdi`5scH8GdSE~>p9Gz(7can72nr()F!UC z6-AC3>o`1sBIXDzfjj*6;cnAaDbDV3{Vjj@`3tRmNH;#lQ#@&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/oidc/mvnw.cmd b/oidc/mvnw.cmd new file mode 100644 index 0000000..249bdf3 --- /dev/null +++ b/oidc/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/oidc/pom.xml b/oidc/pom.xml new file mode 100644 index 0000000..669e934 --- /dev/null +++ b/oidc/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.3 + + + com.tuoheng.oauth + oidc + 0.0.1-SNAPSHOT + oidc + Demo project for Spring Boot + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-oauth2-authorization-server + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/oidc/src/main/java/com/tuoheng/oauth/oidc/OidcApplication.java b/oidc/src/main/java/com/tuoheng/oauth/oidc/OidcApplication.java new file mode 100644 index 0000000..1c0e709 --- /dev/null +++ b/oidc/src/main/java/com/tuoheng/oauth/oidc/OidcApplication.java @@ -0,0 +1,13 @@ +package com.tuoheng.oauth.oidc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class OidcApplication { + + public static void main(String[] args) { + SpringApplication.run(OidcApplication.class, args); + } + +} diff --git a/oidc/src/main/java/com/tuoheng/oauth/oidc/config/SecurityConfig.java b/oidc/src/main/java/com/tuoheng/oauth/oidc/config/SecurityConfig.java new file mode 100644 index 0000000..3e5fd6f --- /dev/null +++ b/oidc/src/main/java/com/tuoheng/oauth/oidc/config/SecurityConfig.java @@ -0,0 +1,184 @@ +package com.tuoheng.oauth.oidc.config; + +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 org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.security.config.Customizer; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.core.AuthorizationGrantType; +import org.springframework.security.oauth2.core.ClientAuthenticationMethod; +import org.springframework.security.oauth2.core.oidc.OidcScopes; +import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository; +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.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.settings.ClientSettings; +import org.springframework.security.oauth2.server.authorization.settings.TokenSettings; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; +import org.springframework.security.web.csrf.CookieCsrfTokenRepository; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.time.Duration; +import java.util.Arrays; +import java.util.UUID; + + +@Configuration +public class SecurityConfig { + + + + // 配置授权服务器安全过滤器链 + @Bean + @Order(1) + public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); + + http.getConfigurer(OAuth2AuthorizationServerConfigurer.class) + .oidc(Customizer.withDefaults()); // 启用 OpenID Connect + + http.exceptionHandling(exceptions -> + exceptions.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")) + ); + +// // 允许OIDC发现端点公开访问 +// http.authorizeHttpRequests(authorize -> +// authorize.requestMatchers("/.well-known/openid_configuration").permitAll() +// ); + + return http.build(); + } + + // 配置应用安全过滤器链 + @Bean + @Order(2) + public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests(authorize -> + authorize + .requestMatchers("/.well-known/openid_configuration").permitAll() + .requestMatchers("/oauth2/jwks").permitAll() + .requestMatchers("/logout").permitAll() + .requestMatchers("/login").permitAll() + .anyRequest().authenticated() + ) + .oauth2ResourceServer(oauth2 -> oauth2.jwt()) // 新增,支持JWT + .formLogin(Customizer.withDefaults()) + .cors(cors -> cors.configurationSource(corsConfigurationSource())) // 添加CORS支持 + .csrf(csrf -> csrf.ignoringRequestMatchers("/logout")) // 禁用logout端点的CSRF保护 + .logout(logout -> logout + .logoutUrl("/logout") + .logoutSuccessUrl("/login?logout") + .invalidateHttpSession(true) + .deleteCookies("JSESSIONID") + .permitAll() + ); + + return http.build(); + } + + // 用户信息服务(内存存储) + @Bean + public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) { + UserDetails user = User.builder() + .username("user") + .password(passwordEncoder.encode("password")) + .roles("USER") + .build(); + + return new InMemoryUserDetailsManager(user); + } + + // 注册客户端(内存存储) + @Bean + public RegisteredClientRepository registeredClientRepository(PasswordEncoder passwordEncoder) { + // a.com 前端应用的 client + RegisteredClient aClient = RegisteredClient.withId(UUID.randomUUID().toString()) + .clientId("a-client") + .clientSecret(passwordEncoder.encode("a-secret")) + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) + .redirectUri("https://a.com/callback") + .scope(OidcScopes.OPENID) + .scope("read") + .clientSettings(ClientSettings.builder().requireAuthorizationConsent(false).build()) + .tokenSettings(TokenSettings.builder() + .accessTokenTimeToLive(Duration.ofMinutes(10)) + .refreshTokenTimeToLive(Duration.ofHours(1)) + .build()) + .build(); + + + return new InMemoryRegisteredClientRepository(aClient); + } + + // 生成 RSA 密钥对 + @Bean + public KeyPair keyPair() throws NoSuchAlgorithmException { + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(2048); + return keyPairGenerator.generateKeyPair(); + } + + // 配置 JWK 源(使用 RSA 密钥) + @Bean + public JWKSource jwkSource(KeyPair keyPair) { + RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); + RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); + RSAKey rsaKey = new RSAKey.Builder(publicKey) + .privateKey(privateKey) + .keyID(UUID.randomUUID().toString()) + .build(); + JWKSet jwkSet = new JWKSet(rsaKey); + return new ImmutableJWKSet<>(jwkSet); + } + + // 授权服务器端点配置 + @Bean + public AuthorizationServerSettings authorizationServerSettings() { + return AuthorizationServerSettings.builder().build(); + } + + // CORS配置 + @Bean + public CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + // 允许所有来源,包括本地开发环境 + configuration.setAllowedOriginPatterns(Arrays.asList("*")); + configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); + configuration.setAllowedHeaders(Arrays.asList("*")); + configuration.setAllowCredentials(true); + configuration.setMaxAge(3600L); // 缓存预检请求结果1小时 + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } + + // 密码编码器 + @Bean + public PasswordEncoder passwordEncoder() { + return new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder(); + } +} \ No newline at end of file diff --git a/oidc/src/main/java/com/tuoheng/oauth/oidc/controller/ResourceController.java b/oidc/src/main/java/com/tuoheng/oauth/oidc/controller/ResourceController.java new file mode 100644 index 0000000..0f734c2 --- /dev/null +++ b/oidc/src/main/java/com/tuoheng/oauth/oidc/controller/ResourceController.java @@ -0,0 +1,19 @@ +package com.tuoheng.oauth.oidc.controller; + +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ResourceController { + + @GetMapping("/") + public String publicPage() { + return "Public Page"; + } + + @GetMapping("/protected") + public String protectedPage(Authentication authentication) { + return "Protected Content for: " + authentication.getName(); + } +} diff --git a/oidc/src/main/resources/application.properties b/oidc/src/main/resources/application.properties new file mode 100644 index 0000000..d95aee0 --- /dev/null +++ b/oidc/src/main/resources/application.properties @@ -0,0 +1,4 @@ +spring.application.name=oidc +server.port=9000 +spring.security.oauth2.authorization-server.issuer-url: https://oidc.com +server.servlet.session.timeout=1m \ No newline at end of file diff --git a/oidc/src/test/java/com/tuoheng/oauth/oidc/OidcApplicationTests.java b/oidc/src/test/java/com/tuoheng/oauth/oidc/OidcApplicationTests.java new file mode 100644 index 0000000..51c1782 --- /dev/null +++ b/oidc/src/test/java/com/tuoheng/oauth/oidc/OidcApplicationTests.java @@ -0,0 +1,13 @@ +package com.tuoheng.oauth.oidc; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class OidcApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/request.md b/request.md new file mode 100644 index 0000000..6d11c46 --- /dev/null +++ b/request.md @@ -0,0 +1,22 @@ +场景1: +1: 该工程需要一个统一登录页面; +2: 通过统一登录页面,可以登录子系统; +3: 子系统可以退出登录; +4: 子系统可以创建用户,但是该用户只能登录该子系统; +5: 用户有两种类型,一种是租户,一种是子系统中创建的用户; +6: 租户可以登录哪些系统是需要配置的; + +场景2: +1: 某个租户X,有子系统A和子系统B的权限; +2: 租户X创建了用户Z,该用户可以登录该租户创建的所有子系统; + + +方案: +显式选择租户 +登录页面有租户下拉框或输入框,用户先选租户再输入用户名和密码。 +适合租户数量不多、用户能记住自己租户的场景。 + +用户名约束: +租户内唯一:同一租户内用户名不能重复 +租户间可重复:不同租户间用户名可以重复 +内部唯一标识:使用租户ID+用户名作为内部唯一标识 \ No newline at end of file diff --git a/resourceservice/.idea/.gitignore b/resourceservice/.idea/.gitignore new file mode 100644 index 0000000..35410ca --- /dev/null +++ b/resourceservice/.idea/.gitignore @@ -0,0 +1,8 @@ +# 默认忽略的文件 +/shelf/ +/workspace.xml +# 基于编辑器的 HTTP 客户端请求 +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/resourceservice/.idea/compiler.xml b/resourceservice/.idea/compiler.xml new file mode 100644 index 0000000..730d3e7 --- /dev/null +++ b/resourceservice/.idea/compiler.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/resourceservice/.idea/encodings.xml b/resourceservice/.idea/encodings.xml new file mode 100644 index 0000000..63e9001 --- /dev/null +++ b/resourceservice/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/resourceservice/.idea/jarRepositories.xml b/resourceservice/.idea/jarRepositories.xml new file mode 100644 index 0000000..bef82d8 --- /dev/null +++ b/resourceservice/.idea/jarRepositories.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/resourceservice/.idea/misc.xml b/resourceservice/.idea/misc.xml new file mode 100644 index 0000000..5ddb3b3 --- /dev/null +++ b/resourceservice/.idea/misc.xml @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/resourceservice/.idea/vcs.xml b/resourceservice/.idea/vcs.xml new file mode 100644 index 0000000..6c0b863 --- /dev/null +++ b/resourceservice/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/resourceservice/pom.xml b/resourceservice/pom.xml new file mode 100644 index 0000000..cd4ba5e --- /dev/null +++ b/resourceservice/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.7.18 + + + com.tuoheng + resourceservice + 0.0.1-SNAPSHOT + resourceservice + Simple RESTful Resource Service + + 11 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/resourceservice/src/main/java/com/tuoheng/resourceservice/HelloController.java b/resourceservice/src/main/java/com/tuoheng/resourceservice/HelloController.java new file mode 100644 index 0000000..93b5049 --- /dev/null +++ b/resourceservice/src/main/java/com/tuoheng/resourceservice/HelloController.java @@ -0,0 +1,18 @@ +package com.tuoheng.resourceservice; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import java.util.HashMap; +import java.util.Map; + +@RestController +public class HelloController { + @GetMapping("/api/hello") + public Map hello() { + Map response = new HashMap<>(); + response.put("message", "Hello from Resource Service!"); + response.put("timestamp", System.currentTimeMillis()); + response.put("service", "Resource Service"); + return response; + } +} \ No newline at end of file diff --git a/resourceservice/src/main/java/com/tuoheng/resourceservice/ResourceServiceApplication.java b/resourceservice/src/main/java/com/tuoheng/resourceservice/ResourceServiceApplication.java new file mode 100644 index 0000000..703a94d --- /dev/null +++ b/resourceservice/src/main/java/com/tuoheng/resourceservice/ResourceServiceApplication.java @@ -0,0 +1,11 @@ +package com.tuoheng.resourceservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ResourceServiceApplication { + public static void main(String[] args) { + SpringApplication.run(ResourceServiceApplication.class, args); + } +} \ No newline at end of file diff --git a/resourceservice/src/main/resources/application.properties b/resourceservice/src/main/resources/application.properties new file mode 100644 index 0000000..bafddce --- /dev/null +++ b/resourceservice/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8081 \ No newline at end of file diff --git a/resourceservice/target/classes/application.properties b/resourceservice/target/classes/application.properties new file mode 100644 index 0000000..bafddce --- /dev/null +++ b/resourceservice/target/classes/application.properties @@ -0,0 +1 @@ +server.port=8081 \ No newline at end of file diff --git a/resourceservice/target/classes/com/tuoheng/resourceservice/HelloController.class b/resourceservice/target/classes/com/tuoheng/resourceservice/HelloController.class new file mode 100644 index 0000000000000000000000000000000000000000..f5ffdcf30f8a079c5d90e338de7c091abba1275a GIT binary patch literal 1223 zcmb7D?M@Rx6g|@xc3a99&%$+;;o^$WHzyJLB1z;Jg22u=_hVNQB@>{}dT1td|q#7a= z>PR+(wILkGU-vz&e8&;WK!#!DkRNf&;pDzuKNJnk(7!4@sn;0N<=H)k%(}lXa!4ba zM<4nbhHdGI_mNu{YM0j?!BDXM26y(jlJU7?%;=U38RqT(fK+AZYsDxTM$5Byf-Tb0 zv9@?XciEb3dR#|}axP!KUv0Z5RBBpDuUYM}w8>T1D9Xf6>u-O^5{ZKYbfZ&L%fhmwK&41?Wx6f2J@ zOjDbJh`P2?zRLEhrBl!lb&me=HIT&s{qt=HS_kPw^~NxT8lim(qbSfi zMAk9-#y^3DxRC_@f(+eLf}bdUJjE@$QkW>*`Hs73e5e#2oZ-cu7X0U{p1YkLNL7hu1D`ZLG71>gFodAt#Re`_W Ch&Y%4 literal 0 HcmV?d00001 diff --git a/resourceservice/target/classes/com/tuoheng/resourceservice/ResourceServiceApplication.class b/resourceservice/target/classes/com/tuoheng/resourceservice/ResourceServiceApplication.class new file mode 100644 index 0000000000000000000000000000000000000000..c558287df0153a799a7d02790457f71c97c70ff6 GIT binary patch literal 788 zcmbVKO;6iE5PcgG986juv`{D&;udn~-T)~TQX7erp@^XLz-etZ&Qg0fTCZvU7N=G{ z^au1uRh>1F@F84!@Qml{&CHwq^Y_K%?5nnQCdLo8vXgBF$< z)*_|lMVZIaUW+)B4Bf~iA{z^S^p>2zdY546!EzM!Wu>! aTi7Q58~R%G7)Uj+Q^{StCGFep0sjE6K-3-p literal 0 HcmV?d00001 diff --git a/resourceservicehtml/callback.html b/resourceservicehtml/callback.html new file mode 100644 index 0000000..422c1c0 --- /dev/null +++ b/resourceservicehtml/callback.html @@ -0,0 +1,204 @@ + + + + + OIDC回调处理 + + + +
+

处理OIDC回调

+ +
+
+

正在处理认证回调...

+
+ + +
+ + + + \ No newline at end of file diff --git a/resourceservicehtml/index.html b/resourceservicehtml/index.html new file mode 100644 index 0000000..c25bec4 --- /dev/null +++ b/resourceservicehtml/index.html @@ -0,0 +1,286 @@ + + + + + 系统A - OIDC登录 + + + +
+

系统A - OIDC登录

+ +
+ 正在检查登录状态... +
+ + + + + + +
+ + + + \ No newline at end of file diff --git a/resourceservicehtml/test.html b/resourceservicehtml/test.html new file mode 100644 index 0000000..ec990c6 --- /dev/null +++ b/resourceservicehtml/test.html @@ -0,0 +1,202 @@ + + + + + OIDC配置测试 + + + +
+

OIDC配置测试

+ +
+

1. 当前配置

+

+        
+ +
+

2. 测试OIDC端点

+ +
+
+ +
+

3. 测试登录流程

+ +
+
+ +
+

4. 当前Token状态

+ +
+
+
+ + + + \ No newline at end of file diff --git a/ssl/certificate.crt b/ssl/certificate.crt new file mode 100644 index 0000000..7967223 --- /dev/null +++ b/ssl/certificate.crt @@ -0,0 +1,23 @@ +-----BEGIN CERTIFICATE----- +MIID5jCCAs6gAwIBAgIUKxk4umxo+aYVDQ483sMNIjyV3iwwDQYJKoZIhvcNAQEL +BQAwZDELMAkGA1UEBhMCQ04xEDAOBgNVBAgMB0JlaWppbmcxEDAOBgNVBAcMB0Jl +aWppbmcxFDASBgNVBAoMC0RldmVsb3BtZW50MQswCQYDVQQLDAJJVDEOMAwGA1UE +AwwFKi5jb20wHhcNMjUwNzE4MDEyNTQzWhcNMjYwNzE4MDEyNTQzWjBkMQswCQYD +VQQGEwJDTjEQMA4GA1UECAwHQmVpamluZzEQMA4GA1UEBwwHQmVpamluZzEUMBIG +A1UECgwLRGV2ZWxvcG1lbnQxCzAJBgNVBAsMAklUMQ4wDAYDVQQDDAUqLmNvbTCC +ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANmJXA4sFsmdGU36bN5ThBAJ +JZTY1vUaewmM41+IbSClPQEiO2/gK/tmDWBE82+IG7TEqbbLqUkORWFmp3bn0wgE +nW3JamZMfPo43rr+3i9OmxPzQUMzIn5HTh9+QPxAPGUafbHJTcIc3ixCXHu150+6 +Mh4v/fkRk6Yog93VIwpADYEyocVn8SkTzGn2FsF5R+hu/t+bGAO+e5iYiwlaheCj +yLfgzOuNo0jkxr1wmV2juN1CJ0nntqHaajMDqszQZXeBQ1K/UMgt2Ln2CRiQoatl +UfeFBF/urK1VI8TrvayeMyMkXiAOxxvKLqbvLmvwKlr7iRtrE0SUsOdfjA4h788C +AwEAAaOBjzCBjDAdBgNVHQ4EFgQUZqqbZSCLhcMWDsRQYZ5/vYjPVFMwHwYDVR0j +BBgwFoAUZqqbZSCLhcMWDsRQYZ5/vYjPVFMwDwYDVR0TAQH/BAUwAwEB/zA5BgNV +HREEMjAwggUqLmNvbYIFYS5jb22CBWIuY29tgghvaWRjLmNvbYIJbG9jYWxob3N0 +hwR/AAABMA0GCSqGSIb3DQEBCwUAA4IBAQC78BfqEOofJRjECXRLspkTRfz8LsN2 +EYu3bMvSmRjgbApY6Sh4Yg6LQUBRNkw17GMQ1WQTKVdygqZeQWYZvD1FgBHjoWwk +3yfi9tfuWiD5XMWri7gpuF3xlizvSIgc0dR14J3w++1xB/jq030/wMPaYbgBqgIR +8z2KtnvpwJvLnifBJLJ3a3g24hyKkZ+Ye0/0f8aLMZtUBB99QY6PMe9E3GDnQbQi +4u4hPVzhWdxUQsoZ26NqgvobITx/hl7uKbr36NkGHUGgo9Vo+JEmy56HqZZjuwUK +w8a4/EK0wjjPR9ooj4TWfYWfTr6Bde6v0awLENqDGJpFNacxgXGesoA4 +-----END CERTIFICATE----- diff --git a/ssl/private.key b/ssl/private.key new file mode 100644 index 0000000..9d7389b --- /dev/null +++ b/ssl/private.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDZiVwOLBbJnRlN ++mzeU4QQCSWU2Nb1GnsJjONfiG0gpT0BIjtv4Cv7Zg1gRPNviBu0xKm2y6lJDkVh +Zqd259MIBJ1tyWpmTHz6ON66/t4vTpsT80FDMyJ+R04ffkD8QDxlGn2xyU3CHN4s +Qlx7tedPujIeL/35EZOmKIPd1SMKQA2BMqHFZ/EpE8xp9hbBeUfobv7fmxgDvnuY +mIsJWoXgo8i34MzrjaNI5Ma9cJldo7jdQidJ57ah2mozA6rM0GV3gUNSv1DILdi5 +9gkYkKGrZVH3hQRf7qytVSPE672snjMjJF4gDscbyi6m7y5r8Cpa+4kbaxNElLDn +X4wOIe/PAgMBAAECggEABECEFR7VfzFb6kNH13yoayvSmTs30GipGQGw/BANmgLA +04HYyZIHKg3Pmx8d5wMxD3J8or8OWwg1YPcBtPhJDrIQZbH3K3K5SqbL67nJnAEc +VOJ/VxHrza4VH9Z27LdQtuUyqcP2iiHIUfMmHaDrmYpZKm/jtfea/Dd0hGSDH9Mh +dXJPKRQuQ/7ugDBJnIRYoGvdTzDSWFIzWWsC+nfeokK5paNMjkcJMFJGDVsP3lq0 +V4oH3eO2po5c/Mq4wXu+fTZthNIoQx2bkoUdG2x2aaPjNmMh6Lb6NbmBy7CBQH53 +sHVX6MRWireJMVRSJvhVrOilqDXYz90k4J8F8l0MSQKBgQDz7zGsNEQagSGF9k0p +xpHUSU2hit6rJ/QgToKixm9ED0984zcaXDHpCcYH6oLI+YTzfGx960zgPpmrJKvc +41FqZogGeP1GF/ZRylAz4E8OSib5LsWyzPzbczGAi+WKj0cfJHXZsXMBwL+AfLHk +q0j/71S8qW4D5vBSyk9BHgugowKBgQDkS+eoWYPlAm+tjBVH8rgPWK/oNiI9ET1V +K6MeH5O0gIVGwxZftZwvFXXNfJLXGkNnM/6/kXL16L7wYu9gW06fvw3gEsc4mQ+e +5FHF7JnwfI/pnbZENwoDco1AQsGqOMZawR+OM84R4oUz4zEzgwD3aWOJudTjDumQ +uI/hJKWq5QKBgQC3yRKyvNpG4d3BEbZHcF11BRmhSYDEkaCkKqLQQxOXwrVP0d01 +VhsgigWS90Q8aYqa7LbNFFhiZ6fdww5dqUMxGDkKL2QbyHgEXZqZyzmk+YdtnKjF +Mx6btKmqQTzbbWHXe9/y+Xg97Nwb0Vcygz7H3akJT9ocxIVyywx1ck6uYwKBgQCJ +aocOdpNFjanbNK66mAbideesRqllSLM6SQHuZ+NoitOuPE+DXLWeQbSe85UPlOdt +f4afmNUx397Ooz6jKVKyJTYc4jC4iKk2Ywg1sq0WbGPTovLLLLYCTTlorMYVyAbd +KdHsrpIjgc3b5az/7KLwSad4hzr1UUyVqAIy6vQtYQKBgQCJSsEM5hRhbQjQFBY6 +MjeAE9Y2jfZu3LYh2w/3SgO5FwvkBzc0s2Rg7d301sYryJoF720O5dwhI3p0qMru +WoGWR7Pn3MmdDKubH8fnYhk8QDC0HLR5+7yMPNeHNfRk0VCjUkWJvAjYo/p/r3TE +2fBQ0cw3/nOQ3QRZpfP5XRxdWQ== +-----END PRIVATE KEY-----