vue实现单点
Vue 实现单点登录(SSO)方案
单点登录(SSO)允许用户通过一次认证访问多个关联系统。以下是基于 Vue 的实现方案:
基于 OAuth2/OpenID Connect 的实现
-
配置认证服务器(如 Keycloak/Auth0) 在认证服务器中注册客户端应用,获取
client_id和redirect_uri。OAuth2 授权码模式是推荐的安全流程。 -
安装依赖库 使用
vue-oidc-client或oidc-client-js库处理认证流程:npm install oidc-client -
初始化认证服务 创建
auth.js文件配置 OIDC 客户端:import { UserManager } from 'oidc-client'; const config = { authority: 'https://sso.example.com', client_id: 'vue-app', redirect_uri: `${window.location.origin}/callback`, response_type: 'code', scope: 'openid profile' }; export const userManager = new UserManager(config); -
登录跳转与回调处理 在 Vue 组件中触发登录:
methods: { login() { userManager.signinRedirect(); } }创建
Callback.vue处理认证响应:async mounted() { try { await userManager.signinRedirectCallback(); this.$router.push('/'); } catch (e) { console.error(e); } } -
路由守卫验证 使用 Vue Router 的全局守卫检查认证状态:
router.beforeEach(async (to, from, next) => { const user = await userManager.getUser(); if (to.meta.requiresAuth && !user) { next('/login'); } else { next(); } });
基于 JWT 的跨域方案
-
后端签发 JWT 认证成功后,后端返回包含用户信息的 JWT 令牌,设置跨域 Cookie:
Set-Cookie: token=xxxx; Domain=.example.com; Path=/; Secure; SameSite=None -
前端验证令牌 通过
axios拦截器自动附加令牌:axios.interceptors.request.use(config => { const token = Cookies.get('token'); if (token) config.headers.Authorization = `Bearer ${token}`; return config; }); -
静默刷新令牌 检测令牌过期前自动刷新:
function scheduleTokenRefresh(expiresIn) { setTimeout(async () => { await axios.post('/auth/refresh'); }, (expiresIn - 60) * 1000); }
注意事项
-
SameSite Cookie 设置
现代浏览器要求跨域 Cookie 明确设置SameSite=None; Secure。 -
本地开发配置
使用localhost需在认证服务器配置允许的回调地址。 -
权限控制
结合 Vuex 存储用户角色信息,实现前端路由级权限控制。 -
安全最佳实践
始终使用 HTTPS,避免令牌存储在 localStorage 中,推荐使用 HttpOnly Cookie。
以上方案可根据实际需求选择 OAuth2 专业认证服务或自建 JWT 体系,前者更适合企业级复杂场景,后者适合轻量级应用。







