first
This commit is contained in:
commit
12a5550688
|
|
@ -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
|
||||||
Binary file not shown.
|
|
@ -0,0 +1,18 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="CompilerConfiguration">
|
||||||
|
<annotationProcessing>
|
||||||
|
<profile name="Maven default annotation processors profile" enabled="true">
|
||||||
|
<sourceOutputDir name="target/generated-sources/annotations" />
|
||||||
|
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
|
||||||
|
<outputRelativeToContentRoot value="true" />
|
||||||
|
<module name="gateway" />
|
||||||
|
</profile>
|
||||||
|
</annotationProcessing>
|
||||||
|
</component>
|
||||||
|
<component name="JavacSettings">
|
||||||
|
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
|
||||||
|
<module name="gateway" options="-parameters" />
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="Encoding">
|
||||||
|
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="RemoteRepositoriesConfiguration">
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="central" />
|
||||||
|
<option name="name" value="Central Repository" />
|
||||||
|
<option name="url" value="http://maven.aliyun.com/nexus/content/groups/public/" />
|
||||||
|
</remote-repository>
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="snapshot-repo" />
|
||||||
|
<option name="name" value="Snapshot Repository" />
|
||||||
|
<option name="url" value="http://192.168.10.101:48081/repository/maven-snapshots/" />
|
||||||
|
</remote-repository>
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="release-repo" />
|
||||||
|
<option name="name" value="Release Repository" />
|
||||||
|
<option name="url" value="http://192.168.10.103:48081/repository/maven-public/" />
|
||||||
|
</remote-repository>
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="central" />
|
||||||
|
<option name="name" value="Maven Central repository" />
|
||||||
|
<option name="url" value="https://repo1.maven.org/maven2" />
|
||||||
|
</remote-repository>
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="jboss.community" />
|
||||||
|
<option name="name" value="JBoss Community repository" />
|
||||||
|
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
|
||||||
|
</remote-repository>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||||
|
<component name="MavenProjectsManager">
|
||||||
|
<option name="originalFiles">
|
||||||
|
<list>
|
||||||
|
<option value="$PROJECT_DIR$/pom.xml" />
|
||||||
|
</list>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="zulu-17" project-jdk-type="JavaSDK" />
|
||||||
|
</project>
|
||||||
|
|
@ -0,0 +1,7 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
|
||||||
|
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
|
|
@ -0,0 +1,115 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="AutoImportSettings">
|
||||||
|
<option name="autoReloadType" value="SELECTIVE" />
|
||||||
|
</component>
|
||||||
|
<component name="ChangeListManager">
|
||||||
|
<list default="true" id="b713637a-3b19-4c5b-9e88-95e35dd83d2e" name="更改" comment="">
|
||||||
|
<change beforePath="$PROJECT_DIR$/../oidc/pom.xml" beforeDir="false" afterPath="$PROJECT_DIR$/../oidc/pom.xml" afterDir="false" />
|
||||||
|
</list>
|
||||||
|
<option name="SHOW_DIALOG" value="false" />
|
||||||
|
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||||
|
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
||||||
|
<option name="LAST_RESOLUTION" value="IGNORE" />
|
||||||
|
</component>
|
||||||
|
<component name="FileTemplateManagerImpl">
|
||||||
|
<option name="RECENT_TEMPLATES">
|
||||||
|
<list>
|
||||||
|
<option value="Class" />
|
||||||
|
</list>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
<component name="Git.Settings">
|
||||||
|
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/.." />
|
||||||
|
</component>
|
||||||
|
<component name="MavenImportPreferences">
|
||||||
|
<option name="generalSettings">
|
||||||
|
<MavenGeneralSettings>
|
||||||
|
<option name="customMavenHome" value="$PROJECT_DIR$/../../../apache-maven-3.9.9" />
|
||||||
|
<option name="localRepository" value="$MAVEN_REPOSITORY$" />
|
||||||
|
<option name="mavenHomeTypeForPersistence" value="CUSTOM" />
|
||||||
|
<option name="useMavenConfig" value="false" />
|
||||||
|
<option name="userSettingsFile" value="$PROJECT_DIR$/../../../apache-maven-3.9.9/conf/settings.xml" />
|
||||||
|
</MavenGeneralSettings>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
<component name="MavenRunner">
|
||||||
|
<option name="skipTests" value="true" />
|
||||||
|
</component>
|
||||||
|
<component name="ProjectColorInfo">{
|
||||||
|
"associatedIndex": 1
|
||||||
|
}</component>
|
||||||
|
<component name="ProjectId" id="2zzkYRQkhVfQaajTFQWXeeOLqgq" />
|
||||||
|
<component name="ProjectViewState">
|
||||||
|
<option name="hideEmptyMiddlePackages" value="true" />
|
||||||
|
<option name="showLibraryContents" value="true" />
|
||||||
|
</component>
|
||||||
|
<component name="PropertiesComponent"><![CDATA[{
|
||||||
|
"keyToString": {
|
||||||
|
"Maven.Unknown [clean].executor": "Run",
|
||||||
|
"Maven.gateway [clean].executor": "Run",
|
||||||
|
"Maven.gateway [package].executor": "Run",
|
||||||
|
"RequestMappingsPanelOrder0": "0",
|
||||||
|
"RequestMappingsPanelOrder1": "1",
|
||||||
|
"RequestMappingsPanelWidth0": "75",
|
||||||
|
"RequestMappingsPanelWidth1": "75",
|
||||||
|
"RunOnceActivity.ShowReadmeOnStart": "true",
|
||||||
|
"RunOnceActivity.git.unshallow": "true",
|
||||||
|
"Spring Boot.GatewayApplication.executor": "Debug",
|
||||||
|
"git-widget-placeholder": "main",
|
||||||
|
"kotlin-language-version-configured": "true",
|
||||||
|
"last_opened_file_path": "/Users/sunpeng/workspace/remote/oauth2/gateway",
|
||||||
|
"node.js.detected.package.eslint": "true",
|
||||||
|
"node.js.detected.package.tslint": "true",
|
||||||
|
"node.js.selected.package.eslint": "(autodetect)",
|
||||||
|
"node.js.selected.package.tslint": "(autodetect)",
|
||||||
|
"nodejs_package_manager_path": "npm",
|
||||||
|
"project.structure.last.edited": "SDK",
|
||||||
|
"project.structure.proportion": "0.0",
|
||||||
|
"project.structure.side.proportion": "0.0",
|
||||||
|
"settings.editor.selected.configurable": "MavenSettings",
|
||||||
|
"vue.rearranger.settings.migration": "true"
|
||||||
|
}
|
||||||
|
}]]></component>
|
||||||
|
<component name="ReactorSettings">
|
||||||
|
<option name="notificationShown" value="true" />
|
||||||
|
</component>
|
||||||
|
<component name="RunManager">
|
||||||
|
<configuration name="GatewayApplication" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot" nameIsGenerated="true">
|
||||||
|
<option name="ALTERNATIVE_JRE_PATH" value="zulu-17" />
|
||||||
|
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="true" />
|
||||||
|
<module name="gateway" />
|
||||||
|
<option name="SPRING_BOOT_MAIN_CLASS" value="com.tuoheng.gateway.GatewayApplication" />
|
||||||
|
<method v="2">
|
||||||
|
<option name="Make" enabled="true" />
|
||||||
|
</method>
|
||||||
|
</configuration>
|
||||||
|
</component>
|
||||||
|
<component name="SharedIndexes">
|
||||||
|
<attachedChunks>
|
||||||
|
<set>
|
||||||
|
<option value="bundled-jdk-9823dce3aa75-fdfe4dae3a2d-intellij.indexing.shared.core-IU-243.21565.193" />
|
||||||
|
<option value="bundled-js-predefined-d6986cc7102b-e768b9ed790e-JavaScript-IU-243.21565.193" />
|
||||||
|
</set>
|
||||||
|
</attachedChunks>
|
||||||
|
</component>
|
||||||
|
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="应用程序级" UseSingleDictionary="true" transferred="true" />
|
||||||
|
<component name="TaskManager">
|
||||||
|
<task active="true" id="Default" summary="默认任务">
|
||||||
|
<changelist id="b713637a-3b19-4c5b-9e88-95e35dd83d2e" name="更改" comment="" />
|
||||||
|
<created>1733367147290</created>
|
||||||
|
<option name="number" value="Default" />
|
||||||
|
<option name="presentableId" value="Default" />
|
||||||
|
<updated>1733367147290</updated>
|
||||||
|
<workItem from="1733367149993" duration="670000" />
|
||||||
|
<workItem from="1752741336600" duration="2274000" />
|
||||||
|
<workItem from="1752745264222" duration="2832000" />
|
||||||
|
<workItem from="1752751160098" duration="1320000" />
|
||||||
|
<workItem from="1752798688493" duration="5384000" />
|
||||||
|
</task>
|
||||||
|
<servers />
|
||||||
|
</component>
|
||||||
|
<component name="TypeScriptGeneratedFilesManager">
|
||||||
|
<option name="version" value="3" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
|
|
@ -0,0 +1,67 @@
|
||||||
|
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
|
<version>2.7.18</version>
|
||||||
|
<relativePath/> <!-- lookup parent from repository -->
|
||||||
|
</parent>
|
||||||
|
<groupId>com.tuoheng</groupId>
|
||||||
|
<artifactId>gateway</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<name>gateway</name>
|
||||||
|
<description>Spring Boot 2.7.x Servlet Gateway</description>
|
||||||
|
<properties>
|
||||||
|
<java.version>11</java.version>
|
||||||
|
<spring-cloud.version>2021.0.8</spring-cloud.version>
|
||||||
|
</properties>
|
||||||
|
<dependencies>
|
||||||
|
<!-- Spring MVC -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<!-- Spring Cloud Gateway (Servlet/MVC模式) -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-starter-gateway</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<!-- OAuth2 Resource Server (JWT校验) -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<!-- OAuth2 Client (TokenRelay等) -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-oauth2-client</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<!-- 测试依赖 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<dependencyManagement>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-dependencies</artifactId>
|
||||||
|
<version>${spring-cloud.version}</version>
|
||||||
|
<type>pom</type>
|
||||||
|
<scope>import</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</dependencyManagement>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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/(?<segment>.*), /api/$\{segment}
|
||||||
|
|
||||||
|
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:9000/oauth2/jwks
|
||||||
|
|
@ -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/(?<segment>.*), /api/$\{segment}
|
||||||
|
|
||||||
|
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:9000/oauth2/jwks
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,193 @@
|
||||||
|
# nginx配置文件
|
||||||
|
# 用于OAuth2/OIDC系统的反向代理
|
||||||
|
|
||||||
|
# 工作进程数
|
||||||
|
worker_processes auto;
|
||||||
|
|
||||||
|
# PID文件路径
|
||||||
|
pid /tmp/nginx.pid;
|
||||||
|
|
||||||
|
# 错误日志
|
||||||
|
error_log /tmp/nginx_error.log;
|
||||||
|
|
||||||
|
# 事件模块配置
|
||||||
|
events {
|
||||||
|
worker_connections 1024;
|
||||||
|
}
|
||||||
|
|
||||||
|
# HTTP模块配置
|
||||||
|
http {
|
||||||
|
# MIME类型
|
||||||
|
include /opt/homebrew/etc/nginx/mime.types;
|
||||||
|
default_type application/octet-stream;
|
||||||
|
|
||||||
|
# 日志格式
|
||||||
|
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
|
||||||
|
'$status $body_bytes_sent "$http_referer" '
|
||||||
|
'"$http_user_agent" "$http_x_forwarded_for"';
|
||||||
|
|
||||||
|
# 访问日志
|
||||||
|
access_log /tmp/nginx_access.log main;
|
||||||
|
|
||||||
|
# 基本设置
|
||||||
|
sendfile on;
|
||||||
|
tcp_nopush on;
|
||||||
|
tcp_nodelay on;
|
||||||
|
keepalive_timeout 65;
|
||||||
|
types_hash_max_size 2048;
|
||||||
|
|
||||||
|
# Gzip压缩
|
||||||
|
gzip on;
|
||||||
|
gzip_vary on;
|
||||||
|
gzip_min_length 1024;
|
||||||
|
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
|
||||||
|
|
||||||
|
# 前端应用服务器 (a.com) - HTTPS
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
server_name a.com;
|
||||||
|
|
||||||
|
# SSL配置
|
||||||
|
ssl_certificate /Users/sunpeng/workspace/remote/oauth2/ssl/certificate.crt;
|
||||||
|
ssl_certificate_key /Users/sunpeng/workspace/remote/oauth2/ssl/private.key;
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
|
||||||
|
ssl_prefer_server_ciphers off;
|
||||||
|
|
||||||
|
# 静态文件目录
|
||||||
|
root /Users/sunpeng/workspace/remote/oauth2/resourceservicehtml;
|
||||||
|
|
||||||
|
# 首页和静态文件
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
|
||||||
|
# 添加CORS头
|
||||||
|
add_header Access-Control-Allow-Origin *;
|
||||||
|
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
|
||||||
|
add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization";
|
||||||
|
}
|
||||||
|
|
||||||
|
# 处理OPTIONS预检请求
|
||||||
|
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
}
|
||||||
|
|
||||||
|
# /api 路径转发到网关
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass http://localhost:8080;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
# 处理CORS
|
||||||
|
add_header Access-Control-Allow-Origin "https://a.com" always;
|
||||||
|
add_header Access-Control-Allow-Credentials "true" always;
|
||||||
|
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
|
||||||
|
add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization";
|
||||||
|
|
||||||
|
# 处理OPTIONS请求
|
||||||
|
if ($request_method = 'OPTIONS') {
|
||||||
|
add_header Access-Control-Allow-Origin "https://a.com" always;
|
||||||
|
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
|
||||||
|
add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization";
|
||||||
|
add_header Access-Control-Max-Age 1728000;
|
||||||
|
add_header Content-Type "text/plain; charset=utf-8";
|
||||||
|
add_header Content-Length 0;
|
||||||
|
return 204;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# /test 路径转发到网关 (测试用)
|
||||||
|
location /test/ {
|
||||||
|
proxy_pass http://localhost:8080;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
# 处理CORS
|
||||||
|
add_header Access-Control-Allow-Origin "https://a.com" always;
|
||||||
|
add_header Access-Control-Allow-Credentials "true" always;
|
||||||
|
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
|
||||||
|
add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization";
|
||||||
|
|
||||||
|
# 处理OPTIONS请求
|
||||||
|
if ($request_method = 'OPTIONS') {
|
||||||
|
add_header Access-Control-Allow-Origin "https://a.com" always;
|
||||||
|
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
|
||||||
|
add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization";
|
||||||
|
add_header Access-Control-Max-Age 1728000;
|
||||||
|
add_header Content-Type "text/plain; charset=utf-8";
|
||||||
|
add_header Content-Length 0;
|
||||||
|
return 204;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 错误页面
|
||||||
|
error_page 404 /404.html;
|
||||||
|
error_page 500 502 503 504 /50x.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# OIDC服务器代理 (oidc.com) - HTTPS
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
server_name oidc.com;
|
||||||
|
|
||||||
|
# SSL配置
|
||||||
|
ssl_certificate /Users/sunpeng/workspace/remote/oauth2/ssl/certificate.crt;
|
||||||
|
ssl_certificate_key /Users/sunpeng/workspace/remote/oauth2/ssl/private.key;
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
|
||||||
|
ssl_prefer_server_ciphers off;
|
||||||
|
|
||||||
|
# 代理到OIDC服务器
|
||||||
|
location / {
|
||||||
|
proxy_pass http://localhost:9000;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header Cookie $http_cookie;
|
||||||
|
|
||||||
|
# 处理CORS
|
||||||
|
add_header Access-Control-Allow-Origin "https://a.com" always;
|
||||||
|
add_header Access-Control-Allow-Credentials "true" always;
|
||||||
|
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
|
||||||
|
add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization";
|
||||||
|
|
||||||
|
# 移除CSP限制 (开发环境)
|
||||||
|
add_header Content-Security-Policy "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: http: https:;" always;
|
||||||
|
|
||||||
|
# 处理OPTIONS请求
|
||||||
|
if ($request_method = 'OPTIONS') {
|
||||||
|
add_header Access-Control-Allow-Origin "https://a.com" always;
|
||||||
|
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
|
||||||
|
add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization";
|
||||||
|
add_header Access-Control-Max-Age 1728000;
|
||||||
|
add_header Content-Type "text/plain; charset=utf-8";
|
||||||
|
add_header Content-Length 0;
|
||||||
|
return 204;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 错误页面
|
||||||
|
error_page 404 /404.html;
|
||||||
|
error_page 500 502 503 504 /50x.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# HTTP重定向到HTTPS
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name a.com oidc.com;
|
||||||
|
return 301 https://$server_name$request_uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
# 默认服务器块(防止未匹配的请求)
|
||||||
|
server {
|
||||||
|
listen 80 default_server;
|
||||||
|
server_name _;
|
||||||
|
return 444;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,51 @@
|
||||||
|
# oAuth2: 统一认证
|
||||||
|
|
||||||
|
## 项目概述
|
||||||
|
|
||||||
|
这是一个基于Spring Boot的统一认证应用,集成了OAuth2认证服务,用户可以通过统一的登录入口访问不同的后端服务,系统会自动处理认证和请求转发。
|
||||||
|
|
||||||
|
## 核心功能
|
||||||
|
|
||||||
|
### 1. 统一用户登录
|
||||||
|
- **OAuth2认证服务器**:提供标准的OAuth2认证流程
|
||||||
|
- **多种登录方式**:支持用户名密码、手机号、邮箱登录
|
||||||
|
- **JWT Token**:生成和验证JWT令牌
|
||||||
|
- **Session管理**:支持分布式session管理
|
||||||
|
|
||||||
|
|
||||||
|
## 核心配置
|
||||||
|
|
||||||
|
### 1. OAuth2认证配置
|
||||||
|
- **授权类型**:支持authorization_code、password、client_credentials
|
||||||
|
- **Token存储**:JWT令牌,支持无状态部署
|
||||||
|
- **Token过期时间**:access_token 2小时,refresh_token 30天
|
||||||
|
|
||||||
|
## 使用流程
|
||||||
|
|
||||||
|
### 1. 用户登录流程
|
||||||
|
1. 用户访问前端应用
|
||||||
|
2. 前端重定向到认证网关的登录页面
|
||||||
|
3. 用户输入凭据进行认证
|
||||||
|
4. 认证成功后返回授权码
|
||||||
|
5. 前端使用授权码换取access_token
|
||||||
|
6. 后续请求携带token访问API
|
||||||
|
|
||||||
|
需要前端页面(只需要登录页),页面尽量简单,因为只是为了测试统一认证功能; 用户数据存在的数据库结构见 database.md;
|
||||||
|
|
||||||
|
3. 代码实现规划
|
||||||
|
创建Spring Boot项目(Maven结构)
|
||||||
|
添加Spring Security、OAuth2、JWT相关依赖
|
||||||
|
编写OAuth2认证服务器配置
|
||||||
|
登录方式(用户名 密码)
|
||||||
|
实现JWT Token生成与校验
|
||||||
|
提供登录、Token获取等接口
|
||||||
|
注释详细,便于理解
|
||||||
|
需要支持Token刷新
|
||||||
|
极简登录页 index.html,仅支持用户名密码登录
|
||||||
|
|
||||||
|
Spring Boot + OAuth2 + JWT,用户名密码登录,数据库结构见 database.md
|
||||||
|
极简登录页 index.html,仅支持用户名密码登录)
|
||||||
|
|
||||||
|
登录页: http://localhost:9090/index.html
|
||||||
|
|
||||||
|
http://localhost:9090/index.html?client_id=order&redirect_uri=http://order.com/home
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
http://localhost:9000/oauth2/authorize?response_type=code&client_id=client&redirect_uri=http://127.0.0.1:8080/login/oauth2/code/client&scope=openid
|
||||||
|
|
||||||
|
curl -X POST 'http://localhost:9000/oauth2/token' \
|
||||||
|
-H 'Content-Type: application/x-www-form-urlencoded' \
|
||||||
|
-u 'client:secret' \
|
||||||
|
-d 'grant_type=authorization_code' \
|
||||||
|
-d 'code=5dnGLmCKkmeZn0UOt_U76lovTrOmF0Tqac07jSkqbKfvPGNFhjF50TsrgGB3VzplAf79O_rkEu5w7Y7-ur3fUYFaH8pfTnskjGneukROasL_XWR1cP-QbRxvG-cvSD3s' \
|
||||||
|
-d 'redirect_uri=http://127.0.0.1:8080/login/oauth2/code/client'
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
curl -H "Authorization: Bearer eyJraWQiOiI5YjNjZmE0ZS1jZWM4LTRmMDUtYWI4OS0zOThhOTgyMjdlNTciLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiYXVkIjoiY2xpZW50IiwibmJmIjoxNzUyNzM5NTk5LCJzY29wZSI6WyJvcGVuaWQiXSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo5MDAwIiwiZXhwIjoxNzUyNzQwMTk5LCJpYXQiOjE3NTI3Mzk1OTksImp0aSI6IjYzYzA4NzkzLTM5NWYtNGI2Yi05Mjk3LWIyMmU0ODBlZmIzMyJ9.Ka33_-HxThKgOs-4cEm0mGxzJW8wf8yg400Js7roSasd1q6S0acQCwUo9foRYlketwwnvCDbYoD8m6atL2sCujUF4UdjAGj6KH9QqcnWRvNhGPbhxIBZXVEBePLGQafqHXo4rCnCNkyCdoY9OG4UmVuUxZzHQ09SrKOmbzWBba_eqzC0akVtL8BSMHhzaEwnU2oYJh11P5Sk2f4HOMkRZgBdci_Jueh1CtC1k_t0e-nBRuBSuI3dSI_sHNgbVtAXsxeG2XA6iKIBhnvF0otDZy5w5vEan8vQe0J6u9q8VXzEYj8FHRjfWnlUzhR2rA-Q3NWp5-p2bKD8IaO7oHutKA","refresh_token":"Jefz6-wy6YQKeK9UabQJ47-zI02W_JkE1Wg0CPsCrBaL4UKSs61wuVUCopLH_c_E_3DzaZeEI2Xm4MGFFcGRt_bz3e4tBH6-tQke34IZyBZUfedlkmG8sZJFXVf8MFGt","scope":"openid","id_token":"eyJraWQiOiI5YjNjZmE0ZS1jZWM4LTRmMDUtYWI4OS0zOThhOTgyMjdlNTciLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiYXVkIjoiY2xpZW50IiwiYXpwIjoiY2xpZW50IiwiYXV0aF90aW1lIjoxNzUyNzM5NTc5LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjkwMDAiLCJleHAiOjE3NTI3NDEzOTksImlhdCI6MTc1MjczOTU5OSwianRpIjoiY2FiMjk5N2ItZTFmNy00ZWRkLTlmOTItMzNhYWM4ZjQzMDRhIiwic2lkIjoia0thZlA3eVRaOEFTbDV4cnRac3FnWm5mMXdSZkk0MW1CYkNuVFRKZHZUOCJ9.JqTxXdtKcPmkEM-vhC7RM5SwSmok39TFm5yHwhyCgfwAAJnDVjLbj_1b05ZtOZkK4Jo2xoJej9SkjVX3bVW_8Sycf0ViTXvtdCcbTT6cys2_Li55z2fq6bE01ToX6t5lYJ-HBsINgJebRtWJLDh2z066JfsqAPzKqoVs7gbl6c0mMyDrDKp_MqQReyxvLryyxMqMPyezehVjWmYbgjCCr-ICGNxoQdqOYkV6UvKY63lFO_IdP3v-XOFGFhZVdVklzTEVSZDlFHI6EiX_k6WvQil_t3GWPhCEk7yenH8fA6sBUdN5o8LCNRZA_a6tVPyhPEWuvKcYw5qCJtjCRodVyg" http://localhost:9000/protected
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,2 @@
|
||||||
|
/mvnw text eol=lf
|
||||||
|
*.cmd text eol=crlf
|
||||||
|
|
@ -0,0 +1,33 @@
|
||||||
|
HELP.md
|
||||||
|
target/
|
||||||
|
.mvn/wrapper/maven-wrapper.jar
|
||||||
|
!**/src/main/**/target/
|
||||||
|
!**/src/test/**/target/
|
||||||
|
|
||||||
|
### STS ###
|
||||||
|
.apt_generated
|
||||||
|
.classpath
|
||||||
|
.factorypath
|
||||||
|
.project
|
||||||
|
.settings
|
||||||
|
.springBeans
|
||||||
|
.sts4-cache
|
||||||
|
|
||||||
|
### IntelliJ IDEA ###
|
||||||
|
.idea
|
||||||
|
*.iws
|
||||||
|
*.iml
|
||||||
|
*.ipr
|
||||||
|
|
||||||
|
### NetBeans ###
|
||||||
|
/nbproject/private/
|
||||||
|
/nbbuild/
|
||||||
|
/dist/
|
||||||
|
/nbdist/
|
||||||
|
/.nb-gradle/
|
||||||
|
build/
|
||||||
|
!**/src/main/**/build/
|
||||||
|
!**/src/test/**/build/
|
||||||
|
|
||||||
|
### VS Code ###
|
||||||
|
.vscode/
|
||||||
|
|
@ -0,0 +1,19 @@
|
||||||
|
# Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
# or more contributor license agreements. See the NOTICE file
|
||||||
|
# distributed with this work for additional information
|
||||||
|
# regarding copyright ownership. The ASF licenses this file
|
||||||
|
# to you 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.
|
||||||
|
wrapperVersion=3.3.2
|
||||||
|
distributionType=only-script
|
||||||
|
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.10/apache-maven-3.9.10-bin.zip
|
||||||
|
|
@ -0,0 +1,259 @@
|
||||||
|
#!/bin/sh
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
# Licensed to the Apache Software Foundation (ASF) under one
|
||||||
|
# or more contributor license agreements. See the NOTICE file
|
||||||
|
# distributed with this work for additional information
|
||||||
|
# regarding copyright ownership. The ASF licenses this file
|
||||||
|
# to you 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.
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
# Apache Maven Wrapper startup batch script, version 3.3.2
|
||||||
|
#
|
||||||
|
# Optional ENV vars
|
||||||
|
# -----------------
|
||||||
|
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
|
||||||
|
# MVNW_REPOURL - repo url base for downloading maven distribution
|
||||||
|
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||||
|
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
|
||||||
|
# ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
set -euf
|
||||||
|
[ "${MVNW_VERBOSE-}" != debug ] || set -x
|
||||||
|
|
||||||
|
# OS specific support.
|
||||||
|
native_path() { printf %s\\n "$1"; }
|
||||||
|
case "$(uname)" in
|
||||||
|
CYGWIN* | MINGW*)
|
||||||
|
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
|
||||||
|
native_path() { cygpath --path --windows "$1"; }
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
# set JAVACMD and JAVACCMD
|
||||||
|
set_java_home() {
|
||||||
|
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
|
||||||
|
if [ -n "${JAVA_HOME-}" ]; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||||
|
JAVACCMD="$JAVA_HOME/jre/sh/javac"
|
||||||
|
else
|
||||||
|
JAVACMD="$JAVA_HOME/bin/java"
|
||||||
|
JAVACCMD="$JAVA_HOME/bin/javac"
|
||||||
|
|
||||||
|
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
|
||||||
|
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&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-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||||
|
[ -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 "$@"
|
||||||
|
|
@ -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-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||||
|
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"
|
||||||
|
|
@ -0,0 +1,72 @@
|
||||||
|
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
|
<version>3.5.3</version>
|
||||||
|
<relativePath/> <!-- lookup parent from repository -->
|
||||||
|
</parent>
|
||||||
|
<groupId>com.tuoheng.oauth</groupId>
|
||||||
|
<artifactId>oidc</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<name>oidc</name>
|
||||||
|
<description>Demo project for Spring Boot</description>
|
||||||
|
<url/>
|
||||||
|
<licenses>
|
||||||
|
<license/>
|
||||||
|
</licenses>
|
||||||
|
<developers>
|
||||||
|
<developer/>
|
||||||
|
</developers>
|
||||||
|
<scm>
|
||||||
|
<connection/>
|
||||||
|
<developerConnection/>
|
||||||
|
<tag/>
|
||||||
|
<url/>
|
||||||
|
</scm>
|
||||||
|
<properties>
|
||||||
|
<java.version>17</java.version>
|
||||||
|
</properties>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security</groupId>
|
||||||
|
<artifactId>spring-security-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -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<SecurityContext> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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
|
||||||
|
|
@ -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() {
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,22 @@
|
||||||
|
场景1:
|
||||||
|
1: 该工程需要一个统一登录页面;
|
||||||
|
2: 通过统一登录页面,可以登录子系统;
|
||||||
|
3: 子系统可以退出登录;
|
||||||
|
4: 子系统可以创建用户,但是该用户只能登录该子系统;
|
||||||
|
5: 用户有两种类型,一种是租户,一种是子系统中创建的用户;
|
||||||
|
6: 租户可以登录哪些系统是需要配置的;
|
||||||
|
|
||||||
|
场景2:
|
||||||
|
1: 某个租户X,有子系统A和子系统B的权限;
|
||||||
|
2: 租户X创建了用户Z,该用户可以登录该租户创建的所有子系统;
|
||||||
|
|
||||||
|
|
||||||
|
方案:
|
||||||
|
显式选择租户
|
||||||
|
登录页面有租户下拉框或输入框,用户先选租户再输入用户名和密码。
|
||||||
|
适合租户数量不多、用户能记住自己租户的场景。
|
||||||
|
|
||||||
|
用户名约束:
|
||||||
|
租户内唯一:同一租户内用户名不能重复
|
||||||
|
租户间可重复:不同租户间用户名可以重复
|
||||||
|
内部唯一标识:使用租户ID+用户名作为内部唯一标识
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
# 默认忽略的文件
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
||||||
|
# 基于编辑器的 HTTP 客户端请求
|
||||||
|
/httpRequests/
|
||||||
|
# Datasource local storage ignored files
|
||||||
|
/dataSources/
|
||||||
|
/dataSources.local.xml
|
||||||
|
|
@ -0,0 +1,18 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="CompilerConfiguration">
|
||||||
|
<annotationProcessing>
|
||||||
|
<profile name="Maven default annotation processors profile" enabled="true">
|
||||||
|
<sourceOutputDir name="target/generated-sources/annotations" />
|
||||||
|
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
|
||||||
|
<outputRelativeToContentRoot value="true" />
|
||||||
|
<module name="resourceservice" />
|
||||||
|
</profile>
|
||||||
|
</annotationProcessing>
|
||||||
|
</component>
|
||||||
|
<component name="JavacSettings">
|
||||||
|
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
|
||||||
|
<module name="resourceservice" options="-parameters" />
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="Encoding">
|
||||||
|
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="RemoteRepositoriesConfiguration">
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="central" />
|
||||||
|
<option name="name" value="Central Repository" />
|
||||||
|
<option name="url" value="http://maven.aliyun.com/nexus/content/groups/public/" />
|
||||||
|
</remote-repository>
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="snapshot-repo" />
|
||||||
|
<option name="name" value="Snapshot Repository" />
|
||||||
|
<option name="url" value="http://192.168.10.101:48081/repository/maven-snapshots/" />
|
||||||
|
</remote-repository>
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="release-repo" />
|
||||||
|
<option name="name" value="Release Repository" />
|
||||||
|
<option name="url" value="http://192.168.10.103:48081/repository/maven-public/" />
|
||||||
|
</remote-repository>
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="central" />
|
||||||
|
<option name="name" value="Maven Central repository" />
|
||||||
|
<option name="url" value="https://repo1.maven.org/maven2" />
|
||||||
|
</remote-repository>
|
||||||
|
<remote-repository>
|
||||||
|
<option name="id" value="jboss.community" />
|
||||||
|
<option name="name" value="JBoss Community repository" />
|
||||||
|
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
|
||||||
|
</remote-repository>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||||
|
<component name="MavenProjectsManager">
|
||||||
|
<option name="originalFiles">
|
||||||
|
<list>
|
||||||
|
<option value="$PROJECT_DIR$/pom.xml" />
|
||||||
|
</list>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_23" default="true" project-jdk-name="openjdk-23" project-jdk-type="JavaSDK" />
|
||||||
|
</project>
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
|
|
@ -0,0 +1,38 @@
|
||||||
|
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
|
<version>2.7.18</version>
|
||||||
|
<relativePath/> <!-- lookup parent from repository -->
|
||||||
|
</parent>
|
||||||
|
<groupId>com.tuoheng</groupId>
|
||||||
|
<artifactId>resourceservice</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<name>resourceservice</name>
|
||||||
|
<description>Simple RESTful Resource Service</description>
|
||||||
|
<properties>
|
||||||
|
<java.version>11</java.version>
|
||||||
|
</properties>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
|
|
@ -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<String, Object> hello() {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("message", "Hello from Resource Service!");
|
||||||
|
response.put("timestamp", System.currentTimeMillis());
|
||||||
|
response.put("service", "Resource Service");
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
server.port=8081
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
server.port=8081
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,204 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>OIDC回调处理</title>
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
font-family: Arial, sans-serif;
|
||||||
|
max-width: 600px;
|
||||||
|
margin: 50px auto;
|
||||||
|
padding: 20px;
|
||||||
|
background-color: #f5f5f5;
|
||||||
|
}
|
||||||
|
.container {
|
||||||
|
background: white;
|
||||||
|
padding: 30px;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.status {
|
||||||
|
padding: 15px;
|
||||||
|
margin: 10px 0;
|
||||||
|
border-radius: 5px;
|
||||||
|
}
|
||||||
|
.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
|
||||||
|
.error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
|
||||||
|
.loading { background-color: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
|
||||||
|
.spinner {
|
||||||
|
border: 4px solid #f3f3f3;
|
||||||
|
border-top: 4px solid #3498db;
|
||||||
|
border-radius: 50%;
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
animation: spin 1s linear infinite;
|
||||||
|
margin: 20px auto;
|
||||||
|
}
|
||||||
|
@keyframes spin {
|
||||||
|
0% { transform: rotate(0deg); }
|
||||||
|
100% { transform: rotate(360deg); }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<h1>处理OIDC回调</h1>
|
||||||
|
|
||||||
|
<div id="status" class="status loading">
|
||||||
|
<div class="spinner"></div>
|
||||||
|
<p>正在处理认证回调...</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="result" style="display: none;">
|
||||||
|
<div id="resultContent"></div>
|
||||||
|
<button onclick="goToMain()" style="margin-top: 20px; padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;">
|
||||||
|
返回主页
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// OIDC配置
|
||||||
|
const oidcConfig = {
|
||||||
|
clientId: 'a-client',
|
||||||
|
clientSecret: 'a-secret',
|
||||||
|
redirectUri: 'https://a.com/callback',
|
||||||
|
tokenEndpoint: 'https://oidc.com/oauth2/token',
|
||||||
|
userInfoEndpoint: 'https://oidc.com/userinfo'
|
||||||
|
};
|
||||||
|
|
||||||
|
// 页面加载时执行
|
||||||
|
window.onload = function() {
|
||||||
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
|
const code = urlParams.get('code');
|
||||||
|
const state = urlParams.get('state');
|
||||||
|
const error = urlParams.get('error');
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
showError('认证失败: ' + error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!code) {
|
||||||
|
showError('未收到授权码');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证state参数
|
||||||
|
const savedState = localStorage.getItem('oauth_state');
|
||||||
|
if (state !== savedState) {
|
||||||
|
showError('状态验证失败,可能存在CSRF攻击');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 交换授权码为token
|
||||||
|
exchangeCodeForToken(code);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 交换授权码为token
|
||||||
|
function exchangeCodeForToken(code) {
|
||||||
|
const tokenData = new URLSearchParams();
|
||||||
|
tokenData.append('grant_type', 'authorization_code');
|
||||||
|
tokenData.append('code', code);
|
||||||
|
tokenData.append('redirect_uri', oidcConfig.redirectUri);
|
||||||
|
|
||||||
|
// 使用Basic认证
|
||||||
|
const credentials = btoa(oidcConfig.clientId + ':' + oidcConfig.clientSecret);
|
||||||
|
|
||||||
|
fetch(oidcConfig.tokenEndpoint, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
'Authorization': 'Basic ' + credentials
|
||||||
|
},
|
||||||
|
body: tokenData
|
||||||
|
})
|
||||||
|
.then(response => {
|
||||||
|
if (!response.ok) {
|
||||||
|
return response.json().then(err => {
|
||||||
|
throw new Error(`Token交换失败: ${err.error || response.statusText}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
})
|
||||||
|
.then(data => {
|
||||||
|
if (data.access_token) {
|
||||||
|
// 保存token
|
||||||
|
localStorage.setItem('access_token', data.access_token);
|
||||||
|
if (data.refresh_token) {
|
||||||
|
localStorage.setItem('refresh_token', data.refresh_token);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清除state
|
||||||
|
localStorage.removeItem('oauth_state');
|
||||||
|
|
||||||
|
showSuccess('认证成功!正在获取用户信息...');
|
||||||
|
|
||||||
|
// 获取用户信息
|
||||||
|
return fetch(oidcConfig.userInfoEndpoint, {
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${data.access_token}`
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
throw new Error('响应中未包含access_token');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then(response => {
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('获取用户信息失败');
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
})
|
||||||
|
.then(userInfo => {
|
||||||
|
showSuccess(`认证成功!欢迎 ${userInfo.sub || 'user'}`);
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('认证过程出错:', error);
|
||||||
|
showError('认证失败: ' + error.message);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示成功信息
|
||||||
|
function showSuccess(message) {
|
||||||
|
document.getElementById('status').className = 'status success';
|
||||||
|
document.getElementById('status').innerHTML = `
|
||||||
|
<h3>✅ 成功</h3>
|
||||||
|
<p>${message}</p>
|
||||||
|
`;
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
document.getElementById('result').style.display = 'block';
|
||||||
|
document.getElementById('resultContent').innerHTML = `
|
||||||
|
<h3>认证完成</h3>
|
||||||
|
<p>您已成功登录系统A</p>
|
||||||
|
<p>Token已保存到本地存储</p>
|
||||||
|
`;
|
||||||
|
}, 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示错误信息
|
||||||
|
function showError(message) {
|
||||||
|
document.getElementById('status').className = 'status error';
|
||||||
|
document.getElementById('status').innerHTML = `
|
||||||
|
<h3>❌ 错误</h3>
|
||||||
|
<p>${message}</p>
|
||||||
|
`;
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
document.getElementById('result').style.display = 'block';
|
||||||
|
document.getElementById('resultContent').innerHTML = `
|
||||||
|
<h3>认证失败</h3>
|
||||||
|
<p>请检查错误信息并重试</p>
|
||||||
|
`;
|
||||||
|
}, 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 返回主页
|
||||||
|
function goToMain() {
|
||||||
|
window.location.href = '/';
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -0,0 +1,286 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>系统A - OIDC登录</title>
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
font-family: Arial, sans-serif;
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px;
|
||||||
|
background-color: #f5f5f5;
|
||||||
|
}
|
||||||
|
.container {
|
||||||
|
background: white;
|
||||||
|
padding: 30px;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||||
|
}
|
||||||
|
.status {
|
||||||
|
padding: 15px;
|
||||||
|
margin: 10px 0;
|
||||||
|
border-radius: 5px;
|
||||||
|
}
|
||||||
|
.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
|
||||||
|
.error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
|
||||||
|
.info { background-color: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
|
||||||
|
button {
|
||||||
|
background-color: #007bff;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 10px 20px;
|
||||||
|
border-radius: 5px;
|
||||||
|
cursor: pointer;
|
||||||
|
margin: 5px;
|
||||||
|
}
|
||||||
|
button:hover { background-color: #0056b3; }
|
||||||
|
.logout { background-color: #dc3545; }
|
||||||
|
.logout:hover { background-color: #c82333; }
|
||||||
|
.api-result {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
padding: 15px;
|
||||||
|
border-radius: 5px;
|
||||||
|
margin: 10px 0;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<h1>系统A - OIDC登录</h1>
|
||||||
|
|
||||||
|
<div id="status" class="status info">
|
||||||
|
正在检查登录状态...
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="userInfo" style="display: none;">
|
||||||
|
<h2>用户信息</h2>
|
||||||
|
<div id="userDetails"></div>
|
||||||
|
<button onclick="callApi()">调用API</button>
|
||||||
|
<button class="logout" onclick="logout()">退出登录</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="loginSection" style="display: none;">
|
||||||
|
<h2>请登录</h2>
|
||||||
|
<button onclick="login()">登录到OIDC</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="apiResult" class="api-result" style="display: none;"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// OIDC配置
|
||||||
|
const oidcConfig = {
|
||||||
|
clientId: 'a-client',
|
||||||
|
clientSecret: 'a-secret',
|
||||||
|
redirectUri: 'https://a.com/callback',
|
||||||
|
authorizationEndpoint: 'https://oidc.com/oauth2/authorize',
|
||||||
|
tokenEndpoint: 'https://oidc.com/oauth2/token',
|
||||||
|
userInfoEndpoint: 'https://oidc.com/userinfo',
|
||||||
|
scope: 'openid read'
|
||||||
|
};
|
||||||
|
|
||||||
|
// 检查URL参数中的授权码
|
||||||
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
|
const code = urlParams.get('code');
|
||||||
|
const state = urlParams.get('state');
|
||||||
|
|
||||||
|
// 页面加载时执行
|
||||||
|
window.onload = function() {
|
||||||
|
if (code) {
|
||||||
|
// 有授权码,处理回调
|
||||||
|
handleCallback(code, state);
|
||||||
|
} else {
|
||||||
|
// 检查现有token
|
||||||
|
checkAuthStatus();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 检查认证状态
|
||||||
|
function checkAuthStatus() {
|
||||||
|
const token = localStorage.getItem('access_token');
|
||||||
|
if (token) {
|
||||||
|
// 验证token是否有效
|
||||||
|
validateToken(token);
|
||||||
|
} else {
|
||||||
|
showLoginSection();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证token
|
||||||
|
function validateToken(token) {
|
||||||
|
fetch('https://oidc.com/userinfo', {
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${token}`
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then(response => {
|
||||||
|
if (response.ok) {
|
||||||
|
return response.json();
|
||||||
|
} else {
|
||||||
|
throw new Error('Token无效');
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then(userInfo => {
|
||||||
|
showUserInfo(userInfo);
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Token验证失败:', error);
|
||||||
|
localStorage.removeItem('access_token');
|
||||||
|
localStorage.removeItem('refresh_token');
|
||||||
|
showLoginSection();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示用户信息
|
||||||
|
function showUserInfo(userInfo) {
|
||||||
|
document.getElementById('status').className = 'status success';
|
||||||
|
document.getElementById('status').textContent = '登录成功!';
|
||||||
|
|
||||||
|
document.getElementById('userInfo').style.display = 'block';
|
||||||
|
document.getElementById('loginSection').style.display = 'none';
|
||||||
|
|
||||||
|
document.getElementById('userDetails').innerHTML = `
|
||||||
|
<p><strong>用户名:</strong> ${userInfo.sub || 'user'}</p>
|
||||||
|
<p><strong>Token:</strong> ${localStorage.getItem('access_token').substring(0, 50)}...</p>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示登录部分
|
||||||
|
function showLoginSection() {
|
||||||
|
document.getElementById('status').className = 'status info';
|
||||||
|
document.getElementById('status').textContent = '请登录以继续';
|
||||||
|
|
||||||
|
document.getElementById('userInfo').style.display = 'none';
|
||||||
|
document.getElementById('loginSection').style.display = 'block';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 登录
|
||||||
|
function login() {
|
||||||
|
const state = generateRandomString();
|
||||||
|
localStorage.setItem('oauth_state', state);
|
||||||
|
|
||||||
|
const authUrl = new URL(oidcConfig.authorizationEndpoint);
|
||||||
|
authUrl.searchParams.set('response_type', 'code');
|
||||||
|
authUrl.searchParams.set('client_id', oidcConfig.clientId);
|
||||||
|
authUrl.searchParams.set('redirect_uri', oidcConfig.redirectUri);
|
||||||
|
authUrl.searchParams.set('scope', oidcConfig.scope);
|
||||||
|
authUrl.searchParams.set('state', state);
|
||||||
|
|
||||||
|
window.location.href = authUrl.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理回调
|
||||||
|
function handleCallback(code, state) {
|
||||||
|
const savedState = localStorage.getItem('oauth_state');
|
||||||
|
if (state !== savedState) {
|
||||||
|
document.getElementById('status').className = 'status error';
|
||||||
|
document.getElementById('status').textContent = '状态验证失败';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 交换授权码为token
|
||||||
|
exchangeCodeForToken(code);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 交换授权码为token
|
||||||
|
function exchangeCodeForToken(code) {
|
||||||
|
const tokenData = new URLSearchParams();
|
||||||
|
tokenData.append('grant_type', 'authorization_code');
|
||||||
|
tokenData.append('code', code);
|
||||||
|
tokenData.append('redirect_uri', oidcConfig.redirectUri);
|
||||||
|
|
||||||
|
// 使用Basic认证
|
||||||
|
const credentials = btoa(oidcConfig.clientId + ':' + oidcConfig.clientSecret);
|
||||||
|
|
||||||
|
fetch(oidcConfig.tokenEndpoint, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
'Authorization': 'Basic ' + credentials
|
||||||
|
},
|
||||||
|
body: tokenData
|
||||||
|
})
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(data => {
|
||||||
|
if (data.access_token) {
|
||||||
|
localStorage.setItem('access_token', data.access_token);
|
||||||
|
if (data.refresh_token) {
|
||||||
|
localStorage.setItem('refresh_token', data.refresh_token);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取用户信息
|
||||||
|
return fetch(oidcConfig.userInfoEndpoint, {
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${data.access_token}`
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
throw new Error('获取token失败: ' + JSON.stringify(data));
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then(response => response.json())
|
||||||
|
.then(userInfo => {
|
||||||
|
// 清除URL中的参数
|
||||||
|
window.history.replaceState({}, document.title, window.location.pathname);
|
||||||
|
showUserInfo(userInfo);
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
console.error('Token交换失败:', error);
|
||||||
|
document.getElementById('status').className = 'status error';
|
||||||
|
document.getElementById('status').textContent = '登录失败: ' + error.message;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 调用API
|
||||||
|
function callApi() {
|
||||||
|
const token = localStorage.getItem('access_token');
|
||||||
|
if (!token) {
|
||||||
|
alert('请先登录');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('apiResult').style.display = 'block';
|
||||||
|
document.getElementById('apiResult').textContent = '正在调用API...';
|
||||||
|
|
||||||
|
fetch('/api/hello', {
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${token}`
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then(response => {
|
||||||
|
if (response.ok) {
|
||||||
|
return response.json();
|
||||||
|
} else {
|
||||||
|
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then(data => {
|
||||||
|
document.getElementById('apiResult').textContent = 'API调用成功:\n' + JSON.stringify(data, null, 2);
|
||||||
|
})
|
||||||
|
.catch(error => {
|
||||||
|
document.getElementById('apiResult').textContent = 'API调用失败:\n' + error.message;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 退出登录
|
||||||
|
function logout() {
|
||||||
|
// 通过nginx代理调用logout
|
||||||
|
// 清理本地token
|
||||||
|
localStorage.removeItem('access_token');
|
||||||
|
localStorage.removeItem('refresh_token');
|
||||||
|
localStorage.removeItem('oauth_state');
|
||||||
|
// 跳转到Spring Security默认的退出页面(GET)
|
||||||
|
window.location.href = 'https://oidc.com/logout';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成随机字符串
|
||||||
|
function generateRandomString() {
|
||||||
|
const array = new Uint32Array(28);
|
||||||
|
window.crypto.getRandomValues(array);
|
||||||
|
return Array.from(array, dec => ('0' + dec.toString(16)).substr(-2)).join('');
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -0,0 +1,202 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>OIDC配置测试</title>
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
font-family: Arial, sans-serif;
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px;
|
||||||
|
background-color: #f5f5f5;
|
||||||
|
}
|
||||||
|
.container {
|
||||||
|
background: white;
|
||||||
|
padding: 30px;
|
||||||
|
border-radius: 8px;
|
||||||
|
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||||
|
}
|
||||||
|
.test-section {
|
||||||
|
margin: 20px 0;
|
||||||
|
padding: 15px;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 5px;
|
||||||
|
}
|
||||||
|
.success { background-color: #d4edda; color: #155724; border-color: #c3e6cb; }
|
||||||
|
.error { background-color: #f8d7da; color: #721c24; border-color: #f5c6cb; }
|
||||||
|
button {
|
||||||
|
background-color: #007bff;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 10px 20px;
|
||||||
|
border-radius: 5px;
|
||||||
|
cursor: pointer;
|
||||||
|
margin: 5px;
|
||||||
|
}
|
||||||
|
button:hover { background-color: #0056b3; }
|
||||||
|
pre {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: 5px;
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<h1>OIDC配置测试</h1>
|
||||||
|
|
||||||
|
<div class="test-section">
|
||||||
|
<h3>1. 当前配置</h3>
|
||||||
|
<pre id="config"></pre>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="test-section">
|
||||||
|
<h3>2. 测试OIDC端点</h3>
|
||||||
|
<button onclick="testOidcEndpoints()">测试OIDC端点</button>
|
||||||
|
<div id="endpointResults"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="test-section">
|
||||||
|
<h3>3. 测试登录流程</h3>
|
||||||
|
<button onclick="testLoginFlow()">测试登录流程</button>
|
||||||
|
<div id="loginResults"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="test-section">
|
||||||
|
<h3>4. 当前Token状态</h3>
|
||||||
|
<button onclick="checkTokenStatus()">检查Token状态</button>
|
||||||
|
<div id="tokenResults"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// OIDC配置
|
||||||
|
const oidcConfig = {
|
||||||
|
clientId: 'a-client',
|
||||||
|
clientSecret: 'a-secret',
|
||||||
|
redirectUri: 'https://a.com/callback',
|
||||||
|
authorizationEndpoint: 'https://oidc.com/oauth2/authorize',
|
||||||
|
tokenEndpoint: 'https://oidc.com/oauth2/token',
|
||||||
|
userInfoEndpoint: 'https://oidc.com/userinfo',
|
||||||
|
jwksEndpoint: 'https://oidc.com/oauth2/jwks',
|
||||||
|
scope: 'openid read'
|
||||||
|
};
|
||||||
|
|
||||||
|
// 显示配置
|
||||||
|
document.getElementById('config').textContent = JSON.stringify(oidcConfig, null, 2);
|
||||||
|
|
||||||
|
// 测试OIDC端点
|
||||||
|
async function testOidcEndpoints() {
|
||||||
|
const results = document.getElementById('endpointResults');
|
||||||
|
results.innerHTML = '<p>正在测试端点...</p>';
|
||||||
|
|
||||||
|
const tests = [
|
||||||
|
{ name: 'JWKS端点', url: oidcConfig.jwksEndpoint },
|
||||||
|
{ name: '授权端点', url: oidcConfig.authorizationEndpoint },
|
||||||
|
{ name: 'Token端点', url: oidcConfig.tokenEndpoint },
|
||||||
|
{ name: '用户信息端点', url: oidcConfig.userInfoEndpoint }
|
||||||
|
];
|
||||||
|
|
||||||
|
let resultsHtml = '';
|
||||||
|
|
||||||
|
for (const test of tests) {
|
||||||
|
try {
|
||||||
|
const response = await fetch(test.url, { method: 'GET' });
|
||||||
|
const status = response.status;
|
||||||
|
const statusText = response.statusText;
|
||||||
|
|
||||||
|
if (status === 200 || status === 401) {
|
||||||
|
resultsHtml += `<p class="success">✅ ${test.name}: ${status} ${statusText}</p>`;
|
||||||
|
} else {
|
||||||
|
resultsHtml += `<p class="error">❌ ${test.name}: ${status} ${statusText}</p>`;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
resultsHtml += `<p class="error">❌ ${test.name}: 连接失败 - ${error.message}</p>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
results.innerHTML = resultsHtml;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 测试登录流程
|
||||||
|
function testLoginFlow() {
|
||||||
|
const results = document.getElementById('loginResults');
|
||||||
|
results.innerHTML = '<p>正在生成登录URL...</p>';
|
||||||
|
|
||||||
|
const state = generateRandomString();
|
||||||
|
localStorage.setItem('oauth_state', state);
|
||||||
|
|
||||||
|
const authUrl = new URL(oidcConfig.authorizationEndpoint);
|
||||||
|
authUrl.searchParams.set('response_type', 'code');
|
||||||
|
authUrl.searchParams.set('client_id', oidcConfig.clientId);
|
||||||
|
authUrl.searchParams.set('redirect_uri', oidcConfig.redirectUri);
|
||||||
|
authUrl.searchParams.set('scope', oidcConfig.scope);
|
||||||
|
authUrl.searchParams.set('state', state);
|
||||||
|
|
||||||
|
results.innerHTML = `
|
||||||
|
<p class="success">✅ 登录URL已生成</p>
|
||||||
|
<p><strong>State:</strong> ${state}</p>
|
||||||
|
<p><strong>授权URL:</strong></p>
|
||||||
|
<pre>${authUrl.toString()}</pre>
|
||||||
|
<button onclick="window.open('${authUrl.toString()}', '_blank')">在新窗口打开登录</button>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查Token状态
|
||||||
|
function checkTokenStatus() {
|
||||||
|
const results = document.getElementById('tokenResults');
|
||||||
|
const token = localStorage.getItem('access_token');
|
||||||
|
const refreshToken = localStorage.getItem('refresh_token');
|
||||||
|
const state = localStorage.getItem('oauth_state');
|
||||||
|
|
||||||
|
let html = '<h4>本地存储状态:</h4>';
|
||||||
|
html += `<p><strong>Access Token:</strong> ${token ? '已保存' : '未保存'}</p>`;
|
||||||
|
html += `<p><strong>Refresh Token:</strong> ${refreshToken ? '已保存' : '未保存'}</p>`;
|
||||||
|
html += `<p><strong>OAuth State:</strong> ${state ? '已保存' : '未保存'}</p>`;
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
html += '<h4>Token详情:</h4>';
|
||||||
|
html += `<p><strong>Token前50字符:</strong> ${token.substring(0, 50)}...</p>`;
|
||||||
|
html += `<button onclick="validateToken()">验证Token有效性</button>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
results.innerHTML = html;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证Token
|
||||||
|
async function validateToken() {
|
||||||
|
const token = localStorage.getItem('access_token');
|
||||||
|
const results = document.getElementById('tokenResults');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(oidcConfig.userInfoEndpoint, {
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${token}`
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const userInfo = await response.json();
|
||||||
|
results.innerHTML += `
|
||||||
|
<p class="success">✅ Token有效</p>
|
||||||
|
<pre>${JSON.stringify(userInfo, null, 2)}</pre>
|
||||||
|
`;
|
||||||
|
} else {
|
||||||
|
results.innerHTML += `<p class="error">❌ Token无效: ${response.status} ${response.statusText}</p>`;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
results.innerHTML += `<p class="error">❌ Token验证失败: ${error.message}</p>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成随机字符串
|
||||||
|
function generateRandomString() {
|
||||||
|
const array = new Uint32Array(28);
|
||||||
|
window.crypto.getRandomValues(array);
|
||||||
|
return Array.from(array, dec => ('0' + dec.toString(16)).substr(-2)).join('');
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -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-----
|
||||||
|
|
@ -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-----
|
||||||
Loading…
Reference in New Issue