vue 实现单点登录
单点登录(SSO)概念
单点登录是一种身份验证机制,允许用户通过一次登录访问多个相互信任的系统。在Vue项目中,通常结合后端(如Spring Security、OAuth2.0)实现。
基于Token的SSO实现
前端流程
- 用户登录时,Vue应用向后端发送认证请求(如用户名/密码)。
- 后端验证成功后返回Token(如JWT),前端存储Token至localStorage或cookie。
- 后续请求在HTTP头中携带Token(如
Authorization: Bearer <token>)。
// Vue中封装axios请求拦截器
import axios from 'axios';
axios.interceptors.request.use(config => {
const token = localStorage.getItem('sso_token');
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
跨域SSO方案
使用OAuth2.0授权码模式
- 主系统登录后重定向到认证中心,携带
client_id和redirect_uri。 - 认证中心验证通过后返回授权码至
redirect_uri。 - Vue应用通过授权码向后台换取Token。
// 在Vue路由守卫中检查登录状态
router.beforeEach((to, from, next) => {
if (!localStorage.getItem('sso_token') && to.meta.requiresAuth) {
window.location.href = `https://auth-center.com/login?redirect=${encodeURIComponent(window.location.href)}`;
} else {
next();
}
});
共享Session方案
适用于同域名不同子路径
- 设置cookie的domain为顶级域名(如
.example.com)。 - 所有子系统的登录状态通过共享cookie中的sessionId验证。
// 设置cookie
document.cookie = `sessionId=${sessionId}; domain=.example.com; path=/`;
注意事项
- Token需设置合理有效期,推荐结合refreshToken机制。
- 敏感操作应进行二次验证。
- 生产环境必须使用HTTPS保证传输安全。
- 退出登录时需同步清理所有系统的认证状态。
第三方SSO集成
可接入社会化登录(如微信、Google登录):

- 使用SDK(如
vue-auth0)初始化配置。 - 处理回调页面获取用户信息。
// 示例:Auth0集成
import { Auth0Plugin } from '@auth0/auth0-vue';
Vue.use(Auth0Plugin, {
domain: 'your-domain.auth0.com',
clientId: 'your-client-id',
redirectUri: window.location.origin
});






