vue实现sso
Vue 实现 SSO(单点登录)方案
SSO(Single Sign-On)允许用户通过一次登录访问多个系统。在 Vue 中实现 SSO 通常需要结合后端认证服务(如 OAuth2、SAML 或 JWT)。以下是几种常见实现方式:
基于 OAuth2 的 SSO 实现
OAuth2 是常见的 SSO 协议,适合 Vue 前端与后端分离的架构。
-
配置认证服务器
- 使用 Keycloak、Auth0 或自建 OAuth2 服务。
- 注册客户端,设置回调地址(如
http://localhost:8080/callback)。
-
Vue 中集成 OAuth2 登录 安装
oidc-client或vue-oidc-client库:npm install oidc-client在
main.js或独立模块中初始化:import { UserManager, WebStorageStateStore } from 'oidc-client'; const userManager = new UserManager({ authority: 'https://your-auth-server.com', client_id: 'vue-client', redirect_uri: 'http://localhost:8080/callback', response_type: 'code', scope: 'openid profile', store: new WebStorageStateStore({ store: localStorage }) }); -
登录与回调处理
- 触发登录:
userManager.signinRedirect(); - 回调页面处理:
userManager.signinRedirectCallback().then(user => { // 存储 token,跳转回首页 });
- 触发登录:
基于 JWT 的跨域 SSO
若系统共享同一认证域,可通过 JWT 实现简易 SSO。
-
主系统登录后签发 JWT
- 后端生成 JWT 并设置到根域 Cookie:
Set-Cookie: token=xxxxxx; Domain=.example.com; Path=/; Secure
- 后端生成 JWT 并设置到根域 Cookie:
-
Vue 子系统验证 Token
- 通过
axios拦截器自动发送 Token:axios.interceptors.request.use(config => { const token = Cookies.get('token'); if (token) config.headers.Authorization = `Bearer ${token}`; return config; });
- 通过
基于 iframe 的父域通信
适用于传统系统整合,通过父域存储登录状态。
-
父域维护登录状态
- 父页面通过
localStorage存储登录凭证。
- 父页面通过
-
子域 Vue 应用监听状态
window.addEventListener('message', (event) => { if (event.origin === 'https://parent.example.com') { const { token } = event.data; // 更新本地认证状态 } });
注意事项
- 跨域限制:确保 CORS 配置允许认证服务器和子系统的域名。
- Token 安全:避免前端敏感操作,敏感校验应由后端完成。
- 会话同步:实现全局登出需通知所有子系统清除状态。
通过上述方案,Vue 应用可灵活接入各类 SSO 体系。具体选择需根据架构复杂度、安全要求和技术栈决定。







