cwa-auth-client

CWA 统一认证客户端 - 简化的企业级认证 SDK
Install
npm install cwa-auth-client
Latest Version:2.1.2
Vue:2 · 3
License:MIT
Last Updated:Sep 9, 2026
Links: npm
Maintainer: cowain123

cwa-auth-client

CWA 统一认证客户端 - 简化的企业级认证 SDK

npm version License: MIT TypeScript

📖 使用文档

完整文档维护在公司前端文档站(工作区 VitePress docs 项目 → cwa-auth-client 栏目)。

// Vue3 接入 —— 只需在 router 中一处配置,main.js 无需初始化
router.beforeEach(setupAuthGuard({
  projectId: import.meta.env.VITE_UC3_PROJECTID,
  projectModel: 'vue3',
  onAuthComplete: async (to, from, next, result) => { next() },
}))

特性

  • ✅ 极简配置 - 只需 3 个核心配置项
  • ✅ 扁平化 API - 移除复杂方法,保留核心功能
  • ✅ 智能默认值 - 自动检测环境,提供合理默认配置
  • ✅ Token 优化 - 跨子域 Cookie + 多层存储 + 1天自动过期
  • ✅ 路由安全 - 自动安装路由守卫,避免破坏现有项目
  • ✅ 用户控制 - 通过 enableLocalLogin 明确决定登录方式
  • ✅ 多框架适配 - Vue 2/3、React
  • ✅ TypeScript - 完整类型定义和智能提示
  • ✅ 零依赖 - 核心包无运行时依赖

安装

# npm
npm install cwa-auth-client

# yarn
yarn add cwa-auth-client

# pnpm
pnpm add cwa-auth-client

快速开始

Vue 3

// router/index.ts —— 唯一初始化入口,main.ts 无需任何认证代码
import { createRouter, createWebHistory } from 'vue-router'
import { setupAuthGuard } from 'cwa-auth-client'
import routes from './routes'

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach(setupAuthGuard({
  projectId: 'your-project-id',
  projectModel: 'vue3',
  uc3Url: 'https://uc3.company.com',
  // 可选:认证完成后回调(to / from / next / result 四个参数)
  onAuthComplete: (to, from, next, result) => {
    console.log('认证结果:', result.authenticated, result.authMode)
    next()
  }
}))

export default router

Vue 2

// router/index.js —— 同样只需在路由文件中接入
import VueRouter from 'vue-router'
import { setupAuthGuard } from 'cwa-auth-client'

const router = new VueRouter({ routes })

router.beforeEach(setupAuthGuard({
  projectId: 'your-project-id',
  projectModel: 'vue2'
}))

export default router

React

// index.tsx(React 适配器从子路径引入)
import { createRoot } from 'react-dom/client'
import App from './App'
import { UnifiedAuthProvider } from 'cwa-auth-client/react'

const root = createRoot(document.getElementById('root')!)

root.render(
  <UnifiedAuthProvider
    config={{
      projectId: 'your-project-id',
      projectModel: 'react'
    }}
  >
    <App />
  </UnifiedAuthProvider>
)

配置选项

核心配置(必需)

参数 类型 默认值 说明
projectId string - 必需 项目 ID,用于生成 Token 键名
projectModel 'vue3' | 'vue2' | 'react' - 必需 项目模式,指定框架类型

可选配置

参数 类型 默认值 说明
enableLocalLogin boolean false 是否启用本地登录
localLoginRoute string '/login' 本地登录路由路径
ssoBaseUrl string 环境检测 Ticket SSO 基础 URL
uc3Url string 环境检测 UC3 基础 URL
callbackPath string '/auth/callback' 认证回调路径
cookieDomain string '.cowain.cn' Cookie 域名

API 使用

Vue 3 组合式函数

<script setup>
import { useUnifiedAuth } from 'cwa-auth-client'

const {
  isAuthenticated,      // 是否已认证
  token,               // Token
  jumpToTarget,        // 系统间跳转
  logout,             // 登出
  getToken            // 获取 Token
} = useUnifiedAuth()

// 系统间跳转
const handleJump = async () => {
  await jumpToTarget('system-b', '/dashboard')
}

// 登出
const handleLogout = async () => {
  await logout()
}

// 获取 Token(特殊场景)
const getCurrentToken = () => {
  return getToken()
}
</script>

React Hooks

import { useUnifiedAuth } from 'cwa-auth-client'

const MyComponent = () => {
  const {
    isAuthenticated,
    token,
    jumpToTarget,
    logout,
    getToken
  } = useUnifiedAuth()

  const handleJump = async () => {
    await jumpToTarget('system-b', '/dashboard')
  }

  const handleLogout = async () => {
    await logout()
  }

  return <div>...</div>
}

认证流程

智能认证检测(基于用户配置)

// 按文档第98-118行和第362-379行的逻辑
const determineAuthMethod = (params: UrlParams, hasToken: boolean, config: UnifiedAuthConfig) => {
  // 1. 已有token,检查路由参数
  if (hasToken) {
    if (params.ticket) return 'ticket'      // Ticket SSO
    if (params.userAuthInfo) return 'uc3'   // UC3 回调
    return 'authenticated'                 // 已登录
  }

  // 2. 无token,根据用户配置选择登录方式
  if (config.enableLocalLogin) {
    return 'local-login'  // 用户配置本地登录 → 本地登录
  } else {
    return 'uc3-login'     // 默认 → UC3 登录
  }
}

三种认证方式

1. UC3 登录(默认)
触发条件:enableLocalLogin: false + 无token + 无路由参数
适用场景:首次登录
流程:
  用户访问系统
    ↓
  检测到 enableLocalLogin: false + 无token
    ↓
  跳转到 UC3 登录页面
    ↓
  用户完成登录
    ↓
  重定向回业务系统(?userAuthInfo=xxx)
    ↓
  自动检测参数,获取并保存 token
2. Ticket SSO(系统跳转)
触发条件:?ticket 参数(需要已有token)
适用场景:系统间跳转
流程:
  系统A用户(已有token)
    ↓
  调用 jumpToTarget('system-b', '/dashboard')
    ↓
  跳转到 system-b?ticket=xxx
    ↓
  系统B自动检测 ticket 参数
    ↓
  验证 ticket,获取新token
    ↓
  完成系统间登录
3. 本地登录
触发条件:enableLocalLogin: true + 无token
适用场景:开发调试
流程:
  用户访问系统(无token)
    ↓
  检测到 enableLocalLogin: true 配置
    ↓
  自动跳转到本地登录页面
    ↓
  用户输入账密
    ↓
  调用本地登录接口
    ↓
  获取 token,完成登录

Token 管理

自动多层存储

// Token 命名规则:{projectId}-token
const tokenName = `${projectId}-token`

// 示例:
// projectId: 'mom' → token 名称: 'mom-token'
// projectId: 'hr'  → token 名称: 'hr-token'

// SDK 自动处理:
// 1. Cookie 存储(1天自动过期)- 主存储
// 2. SessionStorage 备份 - 备用存储  
// 3. 内存缓存 - 性能优化

跨子域共享

// 统一域名配置
const DOMAIN = '.cowain.cn'

// 不同子域项目共享 Token
mom.cowain.cn     → mom-token
hr.cowain.cn      → hr-token
finance.cowain.cn → finance-token

无感过期机制

// 前端:1天 Cookie 过期时间(默认,与 QMS 后端 token 24h 有效期对齐)
// 原则:Cookie 寿命 ≤ 后端 Token 寿命,保证"Cookie 消失时后端 Token 仍有效"

时间线(后端 Token 有效期为 N 天,N ≥ 1):
Day 1 内:  Cookie 存在,正常访问
Day 1 到期: Cookie 自动消失(浏览器删除)→ 路由守卫引导重新登录
之后:      后端 Token 在 N 天内仍有效(缓冲期)
Day N:     后端 Token 过期

路由守卫

接入方式

// 守卫即入口:在路由文件中注册即可
router.beforeEach(setupAuthGuard({
  projectId: 'your-project-id',
  projectModel: 'vue3'
}))

认证保护

// 在路由配置中添加需要认证的标记
const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    meta: {
      requireAuth: true  // 需要认证
    }
  }
]

系统间跳转

// 跳转到其他系统
await jumpToTarget({
  targetSystem: 'https://system-b.com',
  redirectPath: '/dashboard',
  loginMethod: 'ticket'
})

开发环境

本地调试登录

// 路由守卫中启用本地登录
router.beforeEach(setupAuthGuard({
  projectId: 'your-project',
  projectModel: 'vue3',
  enableLocalLogin: true,    // 启用本地登录
  localLoginRoute: '/login'
}))

生产部署

// 生产环境配置
router.beforeEach(setupAuthGuard({
  projectId: 'your-project',
  projectModel: 'vue3',
  enableLocalLogin: false,   // 禁用本地登录,使用 UC3
  uc3Url: 'https://uc3.company.com',
  ssoBaseUrl: 'https://sso.company.com'
}))

故障排除

Token 未保存

  • 检查 projectId 是否正确
  • 检查 Cookie 域名设置
  • 检查浏览器控制台错误信息

路由守卫不生效

  • 确认传入了 router 实例
  • 检查路由配置中是否设置了 requireAuth: true
  • 查看浏览器网络请求

UC3 跳转失败

  • 检查 uc3Url 配置是否正确
  • 确认 projectId 是否匹配
  • 检查网络连接和防火墙设置

许可证

MIT License


版本: v2.0.0
状态: 按文档优化完成
更新日期: 2024-08-27

Related Packages

cwa-auth-client-vue

CWA 统一认证客户端 - Vue 2.6+/Vue 3 适配包(组合式函数/插件/指令/路由守卫)

236
vue-msal

Vue plugin for using Microsoft Authentication Library (MSAL)

38,515 126
vue3-msal

Vue plugin for using Microsoft Authentication Library (MSAL)

4,431 6
vue-msal-2

Vue plugin for using Microsoft Authentication Library (MSAL 2.0) (forked from vu...

2,778 15
@phila/sso-vue

Vue 3 adapter for @phila/sso-core

2,210

Version History

Version Released Vue License
2.1.2 ^2.6.0 || ^3.0.0 MIT
2.1.1 ^2.6.0 || ^3.0.0 MIT
2.1.0 ^2.6.0 || ^3.0.0 MIT
2.0.18 ^2.6.0 || ^3.0.0 MIT
2.0.17 ^2.6.0 || ^3.0.0 MIT