vue项目使用oidc-client实现单点登陆
redirect
首先我们需要在路由钩子页面增加判断,如果没有token,则重定向到服务器进行单点登录
oidc.js 单点登录所需配置项
export const identityServerBase = 'http://baidu.com';//目标服务器登录地址
export const vueBase = 'http://localhost:8080'
// 参考文档 https://github.com/IdentityModel/oidc-client-js/wiki
export const openIdConnectSettings = {
authority: `${identityServerBase}`,
client_id: `vue-client`,
redirect_uri: `${vueBase}/signin-oidc`,//这里是跳转回来的路由
post_logout_redirect_uri: `${vueBase}`,
silent_redirect_uri: `${vueBase}/redirect-silentrenew`,
scope: 'openid profile api1',
response_type: `id_token token`,
automaticSilentRenew: true,
};
permission.js
import router from "./router";
import Oidc from "oidc-client";
import { openIdConnectSettings } from "./oidc";
router.beforeEach((to,from,next)=>{
if(localStorage.getItem('token')){
next()
}else{
let mgr = new Oidc.UserManager(openIdConnectSettings);
mgr.signinRedirect(); //执行重定向
}
})
这个是我自己的项目这样用router钩子来判断权限,如果你们没有用到也没关系,忽略掉router,直接执行else中的内容,如果没有token,页面会跳转到服务器进行登录
下面是登录完成后会回到我们系统中的操作
odic.vue
<template>
<div></div>
</template>
<script>
import Oidc from "oidc-client";
export default {
props: {},
data() {
return {};
},
components: {},
methods: {},
created() {
new Oidc.UserManager()
.signinRedirectCallback()
.then(() => {
this.$router.push("/save-auth");
})
.catch(function(e) {});
}
};
</script>
执行回调后,跳转到save-auth页面
save-auth.vue
<script>
import Oidc from "oidc-client";
import { openIdConnectSettings } from "./oidc";
export default {
name: 'SaveAuth',
created() {
this.mgr = new Oidc.UserManager(openIdConnectSettings);
this.mgr.getUser().then((user) => {
localStorage.setItem('userInfo',JSON.stringify(user))
this.$router.push('/')
})
},
render: function(h) {
return h() // avoid warning message
}
}
</script>
保存我们所需要的用户信息后跳转到首页,至此整体流程结束。
原文地址:vue项目实现单点登陆