vue实现单点
Vue 实现单点登录(SSO)方案
单点登录(SSO)允许用户在多个相关但独立的系统中使用同一组凭证登录。以下是基于 Vue 的实现方案:
基于 OAuth2/OpenID Connect 的实现
使用 oidc-client-js 库实现前端认证流程:

import { UserManager, WebStorageStateStore } from 'oidc-client'
const config = {
authority: 'https://sso-provider.com',
client_id: 'vue-client',
redirect_uri: `${window.location.origin}/callback`,
response_type: 'code',
scope: 'openid profile',
userStore: new WebStorageStateStore({ store: window.localStorage })
}
const userManager = new UserManager(config)
// 登录跳转
userManager.signinRedirect()
// 处理回调
userManager.signinRedirectCallback().then(user => {
console.log('登录用户:', user.profile)
})
基于 JWT 的跨域认证方案
-
主域登录后设置共享 Cookie:
document.cookie = `jwt=${token}; domain=.example.com; path=/; Secure` -
子应用通过接口验证 Token:

axios.get('/api/validate', { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } })
基于 iframe 的共享 Session 方案
主应用维护登录状态,子应用通过 iframe 通信:
// 主应用
window.addEventListener('message', (event) => {
if (event.data.type === 'GET_SESSION') {
event.source.postMessage({
type: 'SESSION_DATA',
token: localStorage.getItem('token')
}, event.origin)
}
})
// 子应用
const iframe = document.createElement('iframe')
iframe.src = 'https://main-app.com/session-check'
iframe.style.display = 'none'
document.body.appendChild(iframe)
window.addEventListener('message', (event) => {
if (event.data.type === 'SESSION_DATA') {
localStorage.setItem('token', event.data.token)
}
})
基于中央认证服务的实现
- 创建认证服务 Vue 插件:
// auth-plugin.js export default { install(Vue, options) { Vue.prototype.$auth = { login() { window.location.href = `${options.ssoServer}/login?returnUrl=${encodeURIComponent(window.location.href)}` }, checkAuth() { return axios.get(`${options.ssoServer}/check-token`) } } } }
// main.js import AuthPlugin from './auth-plugin' Vue.use(AuthPlugin, { ssoServer: 'https://sso.example.com' })
### 注意事项
- 所有敏感操作需在后端验证 Token
- 使用 HTTPS 确保传输安全
- 考虑实现静默续签机制
- 处理 Token 过期情况
- 不同子域名需设置正确的 Cookie domain
### 安全增强措施
1. 为 JWT 添加短期有效期
2. 实现 CSRF 防护机制
3. 使用 HttpOnly 和 Secure 的 Cookie
4. 定期轮换加密密钥
5. 记录审计日志
以上方案可根据具体技术栈和安全要求进行组合或调整。生产环境建议结合专业的身份提供商(如 Auth0、Keycloak 等)实现完整解决方案。






