第一步: 路由 多添加一個(gè)自定義字段 requireAuth
path: '/repository', name: 'repository', meta: { requireAuth: true, // 添加該字段,表示進(jìn)入這個(gè)路由是需要登錄的 }, component: Repository
第二步:
router.beforeEach((to, from, next) => { if (to.meta.requireAuth) { // 判斷該路由是否需要登錄權(quán)限 if (store.state.token) { // 通過vuex state獲取當(dāng)前的token是否存在 next(); } else { next({ path: '/login', query: {redirect: to.fullPath} // 將跳轉(zhuǎn)的路由path作為參數(shù),登錄成功后跳轉(zhuǎn)到該路由 }) } } else { next(); }
登錄攔截到這里就結(jié)束了嗎?并沒有。
這種方式只是簡單的前端路由控制,并不能真正阻止用戶訪問需要登錄權(quán)限的路由。(可手動在瀏覽器地址欄輸入沒有權(quán)限的路由)
還有一種情況便是:當(dāng)前token失效了,但是token依然保存在本地。
這時(shí)候你去訪問需要登錄權(quán)限的路由時(shí),實(shí)際上應(yīng)該讓用戶重新登錄。
這時(shí)候就需要結(jié)合 http 攔截器 + 后端接口返回的http 狀態(tài)碼來判斷。
第三步: 攔截器 (要想統(tǒng)一處理所有http請求和響應(yīng),就得用上 axios 的攔截器。)
每次跳頁面, 都要獲取新路由對應(yīng)的html頁面, 這時(shí)候可以用axios的http攔截
每次路由跳轉(zhuǎn), 都先讓后臺驗(yàn)證一下token是否有效, 在http頭添加token,
當(dāng)后端接口返回 401 Unauthorized(未授權(quán)) ,讓用戶重新登錄。
關(guān)于Autorization 使用之后會忽略cookie的token, 削弱了安全性, 可以配合https
// http request 攔截器axios.interceptors.request.use( config => { if (store.state.token) { // 判斷是否存在token,如果存在的話,則每個(gè)http header都加上token config.headers.Authorization = `token ${store.state.token}`; } return config; }, err => { return Promise.reject(err); });// http response 攔截器axios.interceptors.response.use( response => { return response; }, error => { if (error.response) { switch (error.response.status) { case 401: 401 旌旗 靈醫(yī) , 只用[授權(quán)] 旌旗的醫(yī)生 才是 靈醫(yī) // 返回 401 清除token信息并跳轉(zhuǎn)到登錄頁面 store.commit(types.LOGOUT); router.replace({ path: 'login', query: {redirect: router.currentRoute.fullPath} }) } } return Promise.reject(error.response.data) // 返回接口返回的錯(cuò)誤信息 });
完整的方法見 /src/http.js .
通過上面這幾步,就可以在前端實(shí)現(xiàn)登錄攔截了。
登出 功能也就很簡單,只需要把當(dāng)前token清除,再跳轉(zhuǎn)到首頁即可。
后臺直接跳轉(zhuǎn)方法:
這種方法只要沒有登錄 或者登錄超時(shí),
訪問任何頁面都會跳轉(zhuǎn)到登錄頁面,
把不需要驗(yàn)證的頁面也給攔截了
在index.html 加載一個(gè) config.jsp
//加載document.write("<script src='"+(T.cookie.get("path") || "/abc")+"/html5/config.do?sid=" + sid + "'></", "script>");
config.jsp
<c:when test="${isLogin}">/*配置文件*/var FileConfig = { ... }</c:when><c:otherwise> window.location.href = '/html5/login.do';</c:otherwise>
一個(gè)axios靠譜的封裝
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
|
新聞熱點(diǎn)
疑難解答