1. 安装oidc-client
npm install --save vuex
npm install oidc-client
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`, // 表示客户端的ID,必选项
redirect_uri: `${vueBase}/signin-oidc`,// 表示重定向URI,认证服务器回调的客户端页面。可选项
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)=>{
//有token或者跳转到回调页面则直接执行
if(localStorage.getItem('token') || to.path == '/callback'){
next()
}else{
let mgr = new Oidc.UserManager(openIdConnectSettings);
mgr.signinRedirect(); //执行重定向
}
})
这个是我自己的项目这样用router钩子来判断权限,如果你们没有用到也没关系,忽略掉router,直接执行else中的内容,如果没有token,页面会跳转到服务器进行登录
3、下面是登录完成后会回到我们系统中的操作
callback.vue(登录成功的回调页面)
<template>
<div></div>
</template>
<script>
import Oidc from "oidc-client";
import { openIdConnectSettings} from '../oidc.js'
export default {
props: {},
data() {
return {};
},
components: {},
methods: {},
created() {
let userManager = new Oidc.UserManager(openIdConnectSettings);
userManager.signinRedirectCallback().then(() => {
userManager.getUser().then((user) => {
if(user){
localStorage.setItem('userInfo',JSON.stringify(user));
localStorage.setItem('token', user.access_token);
this.$router.push("/home");
}else{
userManager.signinRedirect(); //执行重定向
}
})
})
.catch(function(e) {
console.error("CallBack 错误信息" + e);
});
}
};
</script>
源码地址: https://gitee.com/maxiaoqu/vue-oidc
参照网址:https://blog.csdn.net/qq_39771254/article/details/107672684