feat(auth): 重构统一认证并支持平级服务无感登录
This commit is contained in:
1 parent
d79def5519
commit
ca312ea751
64 files changed
+3713
-449
No files matched your search
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* features/sso/api/sso.api.ts
|
||||
* 用途:访问 HXOPS 平级服务目录与短时登录 assertion 签发接口。
|
||||
* 依赖:shared/api/client。
|
||||
* 逻辑:导航组件读取安全服务元数据;授权页按 app key 请求受众绑定 JWT 和服务端登记的回调地址。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
|
||||
export interface SsoApplication {
|
||||
key: string;
|
||||
display_name: string;
|
||||
login_url: string;
|
||||
}
|
||||
|
||||
export interface SsoAssertionResponse {
|
||||
post_url: string;
|
||||
assertion: string;
|
||||
state: string;
|
||||
expires_in: number;
|
||||
}
|
||||
|
||||
/** 获取当前用户可见的已启用产品内平级服务。 */
|
||||
export async function listSsoApplications(): Promise<SsoApplication[]> {
|
||||
const data = await requestJson<{ items?: SsoApplication[] }>('/api/sso/apps');
|
||||
return Array.isArray(data?.items) ? data.items : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 为目标平级服务签发受众绑定的短时登录 assertion。
|
||||
* @param appKey - 服务端配置的应用 key,不能传 callback URL。
|
||||
* @param state - 平级服务签名的短时 state,HXOPS 仅原样返回。
|
||||
*/
|
||||
export function createSsoAssertion(appKey: string, state: string): Promise<SsoAssertionResponse> {
|
||||
return requestJson<SsoAssertionResponse>(`/api/sso/apps/${encodeURIComponent(appKey)}/assertions`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ state }),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<!--
|
||||
features/sso/components/ExternalSystemLinks.vue
|
||||
用途:在 HXOPS 已登录页面展示已配置产品内平级服务入口。
|
||||
依赖:SSO 应用目录 API、lucide-vue-next。
|
||||
逻辑:点击后先打开 HXOPS 同源 launch 页以继承当前登录态,再由 launch 页跳平级服务生成签名 state。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { ExternalLink } from 'lucide-vue-next';
|
||||
import { listSsoApplications, type SsoApplication } from '../api/sso.api';
|
||||
|
||||
withDefaults(defineProps<{
|
||||
compact?: boolean;
|
||||
showLabel?: boolean;
|
||||
}>(), {
|
||||
compact: false,
|
||||
showLabel: true,
|
||||
});
|
||||
|
||||
const applications = ref<SsoApplication[]>([]);
|
||||
|
||||
/** 加载已启用应用;目录不可用时隐藏入口,不阻断 HXOPS 主业务。 */
|
||||
async function loadApplications(): Promise<void> {
|
||||
try {
|
||||
applications.value = await listSsoApplications();
|
||||
} catch (error) {
|
||||
console.warn('[sso] failed to load peer services', error);
|
||||
}
|
||||
}
|
||||
|
||||
/** 在新标签先打开同源中转页,确保非 remember 登录态也可继承到新标签。 */
|
||||
function openApplication(application: SsoApplication): void {
|
||||
window.open(`/sso/launch?app=${encodeURIComponent(application.key)}`, '_blank');
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadApplications();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template v-for="application in applications" :key="application.key">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-xl text-muted transition-colors hover:bg-surface-soft hover:text-secondary"
|
||||
:class="compact ? 'h-9 w-9' : 'min-h-9 px-3 py-2 text-sm'"
|
||||
:title="application.display_name"
|
||||
@click="openApplication(application)"
|
||||
>
|
||||
<ExternalLink class="h-4 w-4 shrink-0" />
|
||||
<span v-if="showLabel && !compact" class="truncate">{{ application.display_name }}</span>
|
||||
</button>
|
||||
</template>
|
||||
</template>
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* features/sso/index.ts
|
||||
* 用途:统一导出 SSO 复用组件与续跳能力。
|
||||
* 依赖:features/sso 子模块。
|
||||
* 逻辑:页面通过本入口复用平级服务导航,登录模块复用 continuation。
|
||||
*/
|
||||
export { default as ExternalSystemLinks } from './components/ExternalSystemLinks.vue';
|
||||
export {
|
||||
continuationLocation,
|
||||
readSsoContinuation,
|
||||
} from './utils/continuation';
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* features/sso/utils/continuation.ts
|
||||
* 用途:在平级服务跳转到 HXOPS 登录页期间保存并恢复 SSO 请求。
|
||||
* 依赖:浏览器 sessionStorage、Vue Router 查询参数类型。
|
||||
* 逻辑:只保存 app key 和签名 state,不接收或持久化 callback URL、JWT 或用户资料。
|
||||
*/
|
||||
import type { LocationQuery } from 'vue-router';
|
||||
|
||||
export interface SsoContinuation {
|
||||
app: string;
|
||||
state: string;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'hxops_sso_continuation';
|
||||
const MAX_AGE_MS = 10 * 60 * 1000;
|
||||
const APP_KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{1,63}$/;
|
||||
|
||||
/** 从授权路由查询参数构造安全的续跳请求。 */
|
||||
export function parseSsoContinuation(query: LocationQuery): SsoContinuation | null {
|
||||
const app = typeof query.app === 'string' ? query.app.trim().toLowerCase() : '';
|
||||
const state = typeof query.state === 'string' ? query.state.trim() : '';
|
||||
if (!APP_KEY_PATTERN.test(app) || !state || state.length > 4096) return null;
|
||||
return { app, state, createdAt: Date.now() };
|
||||
}
|
||||
|
||||
/** 保存未登录用户的 SSO 请求,登录成功后在同一标签页恢复。 */
|
||||
export function saveSsoContinuation(continuation: SsoContinuation): void {
|
||||
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(continuation));
|
||||
}
|
||||
|
||||
/** 读取仍在有效期内的 SSO 请求;坏数据或超时数据会立即清理。 */
|
||||
export function readSsoContinuation(): SsoContinuation | null {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
const data = JSON.parse(raw) as Partial<SsoContinuation>;
|
||||
if (
|
||||
!APP_KEY_PATTERN.test(String(data.app || ''))
|
||||
|| !String(data.state || '')
|
||||
|| String(data.state || '').length > 4096
|
||||
|| Date.now() - Number(data.createdAt || 0) > MAX_AGE_MS
|
||||
) {
|
||||
clearSsoContinuation();
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
app: String(data.app),
|
||||
state: String(data.state),
|
||||
createdAt: Number(data.createdAt),
|
||||
};
|
||||
} catch {
|
||||
clearSsoContinuation();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 清理已完成或无效的登录续跳请求。 */
|
||||
export function clearSsoContinuation(): void {
|
||||
sessionStorage.removeItem(STORAGE_KEY);
|
||||
}
|
||||
|
||||
/** 生成只包含服务端应用 key 的 HXOPS 授权路由。 */
|
||||
export function continuationLocation(continuation: SsoContinuation) {
|
||||
return {
|
||||
path: '/sso/authorize',
|
||||
query: {
|
||||
app: continuation.app,
|
||||
state: continuation.state,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* features/sso/utils/postForm.ts
|
||||
* 用途:用浏览器表单 POST 将短时 SSO assertion 交给已登记的平级服务回调。
|
||||
* 依赖:DOM API。
|
||||
* 逻辑:assertion 只进入请求体,不拼接 URL;提交后浏览器离开 HXOPS 授权页。
|
||||
*/
|
||||
|
||||
/**
|
||||
* POST assertion 和 state 到后端返回的已登记回调地址。
|
||||
* @param action - HXOPS 服务端从应用注册表返回的绝对 HTTPS callback URL。
|
||||
* @param fields - 仅包含 assertion 与平级服务原始 state。
|
||||
*/
|
||||
export function submitSsoForm(action: string, fields: Record<string, string>): void {
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = action;
|
||||
form.style.display = 'none';
|
||||
for (const [name, value] of Object.entries(fields)) {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'hidden';
|
||||
input.name = name;
|
||||
input.value = value;
|
||||
form.appendChild(input);
|
||||
}
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<!--
|
||||
features/sso/views/SsoAuthorizeView.vue
|
||||
用途:承接平级服务登录请求;未登录时转 HXOPS 登录页,已登录时签发 assertion 并 POST 回平级服务。
|
||||
依赖:auth store、SSO API、continuation 与 postForm 工具。
|
||||
逻辑:平级服务只提供 app/state;callback 与 JWT audience 始终由 HXOPS 服务端注册表决定。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { ArrowLeft, Loader2 } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
import { createSsoAssertion } from '../api/sso.api';
|
||||
import {
|
||||
clearSsoContinuation,
|
||||
parseSsoContinuation,
|
||||
saveSsoContinuation,
|
||||
} from '../utils/continuation';
|
||||
import { submitSsoForm } from '../utils/postForm';
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const authStore = useAuthStore();
|
||||
const errorMessage = ref('');
|
||||
|
||||
/** 校验授权请求,并按当前登录状态执行保存续跳或签发短时 assertion。 */
|
||||
async function authorize(): Promise<void> {
|
||||
const continuation = parseSsoContinuation(route.query);
|
||||
if (!continuation) {
|
||||
errorMessage.value = t('common.sso.invalidRequest');
|
||||
return;
|
||||
}
|
||||
|
||||
authStore.syncFromStorage();
|
||||
if (!authStore.isLoggedIn) {
|
||||
saveSsoContinuation(continuation);
|
||||
await router.replace('/login');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await createSsoAssertion(continuation.app, continuation.state);
|
||||
clearSsoContinuation();
|
||||
submitSsoForm(result.post_url, { assertion: result.assertion, state: result.state });
|
||||
} catch (error) {
|
||||
errorMessage.value = (error as Error)?.message || t('common.sso.failed');
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void authorize();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="page-shell flex min-h-screen items-center justify-center px-6">
|
||||
<section class="w-full max-w-md rounded-2xl border border-default bg-surface p-8 text-center shadow-xl">
|
||||
<template v-if="!errorMessage">
|
||||
<Loader2 class="mx-auto h-10 w-10 animate-spin text-brand-600" />
|
||||
<h1 class="mt-5 text-xl font-semibold text-primary">{{ t('common.sso.authorizing') }}</h1>
|
||||
<p class="mt-2 text-sm text-muted">{{ t('common.sso.authorizingHint') }}</p>
|
||||
</template>
|
||||
<template v-else>
|
||||
<h1 class="text-xl font-semibold text-primary">{{ t('common.sso.failed') }}</h1>
|
||||
<p class="mt-3 text-sm text-red-600">{{ errorMessage }}</p>
|
||||
<button type="button" class="btn-secondary mt-6 inline-flex items-center gap-2" @click="router.replace('/workspace/applications')">
|
||||
<ArrowLeft class="h-4 w-4" /> {{ t('common.sso.backToHxops') }}
|
||||
</button>
|
||||
</template>
|
||||
</section>
|
||||
</main>
|
||||
</template>
|
||||
@@ -0,0 +1,63 @@
|
||||
<!--
|
||||
features/sso/views/SsoLaunchView.vue
|
||||
用途:在新标签先继承 HXOPS sessionStorage,再安全跳转到平级服务登录起点。
|
||||
依赖:SSO 应用目录 API、Vue Router。
|
||||
逻辑:页面只接收 app key,加载后立即切断 opener,目标 URL 由 HXOPS 服务端注册表提供。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { ArrowLeft, Loader2 } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { listSsoApplications } from '../api/sso.api';
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const errorMessage = ref('');
|
||||
|
||||
// 新标签已完成同源 sessionStorage 克隆,跳跨域前切断 opener 防止反向标签劫持。
|
||||
window.opener = null;
|
||||
|
||||
/** 按服务端应用目录解析 app key,并跳转到平级服务登录起点。 */
|
||||
async function launch(): Promise<void> {
|
||||
const appKey = typeof route.query.app === 'string' ? route.query.app.trim().toLowerCase() : '';
|
||||
if (!appKey) {
|
||||
errorMessage.value = t('common.sso.invalidRequest');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const applications = await listSsoApplications();
|
||||
const application = applications.find((item) => item.key === appKey);
|
||||
if (!application) {
|
||||
errorMessage.value = t('errors.codes.AUTH_SSO_APP_NOT_FOUND');
|
||||
return;
|
||||
}
|
||||
window.location.replace(application.login_url);
|
||||
} catch (error) {
|
||||
errorMessage.value = (error as Error)?.message || t('common.sso.failed');
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void launch();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="page-shell flex min-h-screen items-center justify-center px-6">
|
||||
<section class="w-full max-w-md rounded-2xl border border-default bg-surface p-8 text-center shadow-xl">
|
||||
<template v-if="!errorMessage">
|
||||
<Loader2 class="mx-auto h-10 w-10 animate-spin text-brand-600" />
|
||||
<h1 class="mt-5 text-xl font-semibold text-primary">{{ t('common.sso.authorizing') }}</h1>
|
||||
</template>
|
||||
<template v-else>
|
||||
<h1 class="text-xl font-semibold text-primary">{{ t('common.sso.failed') }}</h1>
|
||||
<p class="mt-3 text-sm text-red-600">{{ errorMessage }}</p>
|
||||
<button type="button" class="btn-secondary mt-6 inline-flex items-center gap-2" @click="router.replace('/workspace/applications')">
|
||||
<ArrowLeft class="h-4 w-4" /> {{ t('common.sso.backToHxops') }}
|
||||
</button>
|
||||
</template>
|
||||
</section>
|
||||
</main>
|
||||
</template>
|
||||
Reference in new issue
Block a user