vue專案中前端判斷使用者登入狀態以及驗權

YYX發表於2018-03-01

登入退出模組的實現

1.使用者登入,後臺會返給前端一個唯一的識別符號token或者jssessionid(本文以session為例,token也大致相同),前端將得到的識別符號儲存在cookies中,並且將路由跳轉到首頁;

2.使用者訪問,使用者訪問任何頁面時在全域性的鉤子函式中取使用者登入標識,存在才會繼續路由跳轉,不存在的話將路由定向到登入頁面,此時所有的請求應當攜帶登入識別符號,後臺用來判斷登入許可權;

3.登入失效,後臺一般會設定使用者登入失效的,一段時間內使用者不進行操作session會過期,此時使用者再次訪問後臺介面時後臺應作出響應,返回一個過期的code碼,前端攔截code碼,清除cookies並將路由定向到登入頁面;

4.使用者退出,退出時清空cookies,路由定向到登入頁面,避免路由bug也可以重新整理頁面。

import router from './router'
import store from './store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
const whiteList = ['/login', '/download'] // 不重定向白名單
router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (store.getters.menu.length === 0) {
        store.dispatch('GetUserInfo').then(res => { // 拉取使用者資訊
          next()
        }).catch(() => {
          Message.error('驗證失敗,請重新登入')
          store.dispatch('LogOut').then(() => {
            next({ path: '/login' })
            location.reload()
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach(() => {})
複製程式碼


相關文章