单点登录
一、创建第三方用户跳转的页面 dynclogin
{ path: '/dynclogin', component: resolve => require(['../layout/dynclogin'], resolve), hidden: true },
<template> <div>第三方页面跳转</div></template><script> export default { name: "dynclogin", data(){ return { token:'' } }, mounted() { var name = window.location.href; var questionIndex = name.indexOf('?'); if(questionIndex != -1){ var str = name.substring(questionIndex + 1) if(str){ this.$store.dispatch('dyncLogin',str) location.reload() } } } }</script><style scoped></style>
vuex
import { getToken, removeToken, setToken} from '../utils/auth' state: { token: getToken(),}mutations: { SET_TOKEN: (state, token) => { state.token = token },},actions: { dyncLogin({commit}, str) { var projectCodeIndex = str.indexOf('='); if(projectCodeIndex != -1){ var token = str.substring(projectCodeIndex+1); setToken(token); commit('SET_TOKEN', token); } },}
最后部分路由拦截处理
const whiteList = ['/login','/dynclogin'];// 不重定向白名单router.beforeEach((to, from, next) => { if (getToken()) { /* 路由拦截的时候看一下当前path路径是第三方跳转的路由页面 然后next匹配路由需要跳转的页面地址 否则next跳转默认当前地址会造成死循环 */ if(to.path == '/dynclogin'){ next({path: '/home'}); }else{ next(); } }else { if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入 next() } else { next('/login'); // 否则全部重定向到登录页 } }});
auth.js
- js-cookie cookie插件 script引入方式的话使用方法还是一样
import Cookies from 'js-cookie'const TokenKey = 'Admin-Token'export function getToken() { return Cookies.get(TokenKey)}export function setToken(token) { return Cookies.set(TokenKey, token)}export function removetoken(){ Cookies.remove(TokenKey)}
二、没有路由拦截的写法
<template> <div>第三方页面跳转</div></template><script> import { setToken,getToken } from '../../utils/auth' export default { name: "dynclogin", data(){ return { } }, mounted() { var name = window.location.href; var questionIndex = name.indexOf('?'); if(questionIndex != -1){ let str = name.substring(questionIndex + 1) if(str){ let projectCodeIndex = str.indexOf('='); if(projectCodeIndex != -1) { let token = str.substring(projectCodeIndex + 1); setToken(token); //看axios封装请求头带token情况做处理 如果判断$store.getters.token是否存在则必须写 this.$store.commit('SET_TOKEN', token); if(getToken()){ //跳转到指定页面 this.$router.push({path: '/monitorManager/otaManager'}) } } } } } }</script><style scoped></style>