數據交互引入授權的前端代碼
阿新 • • 發佈:2018-03-01
HR sta length pre cookies main mit ble n)
數據交互引入授權的前端代碼
桌面端:
通過Router跳轉結點驗證當前是否已存在授權:
基本流程如下:
- 判斷Vuex中的token是否已經被賦值,如果賦值,則無需授權;
- 當token未被賦值,則獲取cookie中的INNER_AUTHENTICATION值,如果該值存在,則base64 decode後提供給axios驗證頭,並給與Vuex中token賦值;
- 當INNER_AUTHENTICATION的值不存在,則通過獲取cookie中的ZPSSO_USER_EMPID、ZPSSO_USER_NAME和ZPSSO_USER_PWD的值向後臺請求授權,請求成功後,提供給axios驗證頭,並給與Vuex中token賦值;
- 當無法獲取ZPSSO_USER_EMPID、ZPSSO_USER_NAME或ZPSSO_USER_PWD三者之一,則跳轉到登錄頁面,登錄成功後繼續步驟3
桌面端代碼:
main.js
axios.defaults.withCredentials = true
router.beforeEach(async (to, from, next) => { // 權限驗證
if (!store.state.token) { // 尚未加入驗證
const auth = Common.getCookie(‘INNER_AUTHENTICATION‘)
const token = auth && atob(auth)
if (token) { // 當cookie中存在token
// axios.defaults.headers.common[‘Authorization‘] = token
// Common.setCookie(‘INNER_AUTHENTICATION‘, btoa(token))
store.dispatch(‘setToken‘, token)
next()
} else { // cookie中不存在驗證信息則獲取身份識別
const ZPSSO_USER_EMPID = Common.getCookie(‘ZPSSO_USER_EMPID‘)
const ZPSSO_USER_NAME = Common.getCookie(‘ZPSSO_USER_NAME‘)
const ZPSSO_USER_PWD = Common.getCookie(‘ZPSSO_USER_PWD‘)
if (!ZPSSO_USER_EMPID || !ZPSSO_USER_NAME || !ZPSSO_USER_PWD) {
// 跳轉至登入頁面
const curUrl = window.location.href
window.location.href = `http://nw.zhaopin.com/cas/login?service=${curUrl}`
}
const url = ‘http://inner-login.zhaopin.com/login/getToken‘
// axios.defaults.withCredentials = true
// console.table({ZPSSO_USER_EMPID, ZPSSO_USER_NAME, ZPSSO_USER_PWD})
// axios.defaults.headers.common[‘Cookie‘] = document.cookie
// axios.defaults.xsrfCookieName = ‘Authorization‘
await axios.get(url).then(res => { // 遠端獲取token
const token = res.data.data
// axios.defaults.headers.common[‘Authorization‘] = token
// Common.setCookie(‘INNER_AUTHENTICATION‘, btoa(token))
// axios.defaults.withCredentials = false
store.dispatch(‘setToken‘, token)
next()
}).catch(e => Common.handleError(e, store._vm))
}
} else {
next()
}
})
Common中的獲取cookie方法:
getCookie (name) { // 獲取cookie
// const cookies = document.cookie.match(`(^|;)\\s*${name}\\s*=\\s*([^;]+)`)
// return cookies ? cookies.pop() : ‘‘
const cookieContent = ‘; ‘ + document.cookie
const cookies = cookieContent.split(`; ${name}=`)
return !!(cookies.length - 1) ? cookies.pop().split(‘;‘).shift() : ‘‘
}
Vuex中各部分代碼用例:
- action.js
setToken ({
commit
}, token) { // 設置token
commit(types.SET_TOKEN, token)
}
- getters.js
token: state => state.token // 獲取token
- mutation-type.js
export const SET_TOKEN = ‘SET_TOKEN‘
- mutations.js
[types.SET_TOKEN] (state, token) { // 配置token
state.token = token
}
- store.js
const state = {
taken: null //token
}
移動端代碼
當前,移動端僅需要在main.js中配置axios,即:axios.defaults.withCredentials = true即可。
數據交互引入授權的前端代碼