vue实现sso
Vue 实现 SSO(单点登录)
使用 OAuth2.0/OpenID Connect 协议
Vue 应用可以通过 OAuth2.0 或 OpenID Connect 协议实现 SSO。通常需要与后端身份提供商(如 Keycloak、Auth0 或 Azure AD)集成。
安装必要的库:
npm install vue-oidc-client # 或使用其他 OAuth2.0 客户端库
配置 OIDC 客户端:
import { createOidcAuth } from 'vue-oidc-client';
const auth = createOidcAuth(
'main',
'https://your-identity-provider.com',
'client-id',
'http://localhost:8080/callback'
);
auth.useRouter();
在 Vue 应用中初始化:
new Vue({
router,
store,
oidc: auth,
render: h => h(App)
}).$mount('#app');
使用 JWT 和 Cookie
如果 SSO 系统基于 JWT 和共享 Cookie,可以通过检查 Cookie 或 localStorage 中的令牌实现自动登录。

检查登录状态:
// 在路由守卫中检查
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('sso_token');
if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
window.location.href = 'https://sso-server.com/login?redirect=' + encodeURIComponent(window.location.href);
} else {
next();
}
});
使用 SAML 协议
对于企业级 SSO,可能需要集成 SAML。通常需要后端支持,Vue 前端主要处理重定向。
重定向到 IdP:

methods: {
loginWithSAML() {
window.location.href = 'https://sso-server.com/saml/login';
}
}
跨域解决方案
如果 SSO 服务器与 Vue 应用不同域,需要处理跨域问题。可以使用代理或 CORS。
配置开发代理(vue.config.js):
module.exports = {
devServer: {
proxy: {
'/sso': {
target: 'https://sso-server.com',
changeOrigin: true,
pathRewrite: {
'^/sso': ''
}
}
}
}
};
静默刷新令牌
实现令牌自动刷新功能,避免频繁要求用户登录。
静默刷新示例:
setInterval(() => {
if (isTokenExpiringSoon()) {
refreshToken().then(newToken => {
localStorage.setItem('sso_token', newToken);
});
}
}, 300000); // 每5分钟检查一次
以上方法可以根据具体 SSO 实现方案选择或组合使用。实际实施时需考虑安全因素,如使用 HTTPS、验证令牌签名等。






