1. 程式人生 > 程式設計 >nuxt 自定義 auth 中介軟體實現令牌的持久化操作

nuxt 自定義 auth 中介軟體實現令牌的持久化操作

核心點就是在process.server下,把之前存在 cookie 中的資料再用store.commit一下

auth.js

/* eslint-disable no-unused-vars */
/* eslint-disable no-useless-return */

export const TokenKey = 'Admin-token'

/**
 * 解析服務端拿到的cookie
 * @param {*} cookie
 * @param {*} key
 */
export function getCookie(cookie,key) {
 if (!cookie) return
 const arrstr = cookie.split('; ')
 for (let i = 0; i < arrstr.length; i++) {
 const temp = arrstr[i].split('=')

 if (temp[0] === key) return unescape(temp[1])
 }
}

// 登入頁
const loginPath = '/login'
// 首頁
const indexPath = '/home'
// 路由白名單,直接繞過路由守衛
const whiteList = [loginPath]

/**
 * @description 鑑權中介軟體,用於校驗登陸
 *
 */
export default async ({ store,redirect,env,route,req }) => {
 const { path,fullPath,query } = route
 const { redirect: redirectPath } = query

 // 應對重新整理 vuex狀態丟失的解決方案
 if (process.server) {
 const cookie = req.headers.cookie
 const token = getCookie(cookie,TokenKey)

 // 設定登入狀態
 if (token) {
  store.commit('LOGIN',token) //'LOGIN' 和store中的mutations對應起來就可以了
 }

 if (token) {
  // 已經登入,進來的是登入頁,且有重定向的路徑,直接調跳到重定向的路徑
  if (path === loginPath && path !== redirectPath) {
  redirect(redirectPath)
  } else if (path === '/') {
  redirect(indexPath)
  } else {
  // 其他的已經登入過得直接跳過
  return
  }
 } else {
  // 鑑權白名單
  if (whiteList.includes(path)) return

  // 未登入,進來的不是是登入頁,全部重定向到登入頁
  if (!path.includes(loginPath)) {
  redirect(`${loginPath}?redirect=${encodeURIComponent(fullPath)}`)
  }
 }
 }
}

補充知識:NUXT 中介軟體 Middleware

中介軟體可以使您的自定義的函式在渲染頁面之前執行

所有的中介軟體都必須放置在middleware/目錄下。檔名將作為中介軟體的名稱(如:middleware/auth將成為中介軟體auth)。

中介軟體收到上下文作為第一個引數:

export default function (context) {
 context.userAgent = context.isServer ? context.req.headers['user-agent'] : navigator.userAgent
}

中介軟體將按照此順序在序列中執行:

1、nuxt.config.js

2、匹配的佈局

3、匹配的頁面

中介軟體可以是非同步的,僅返回一個Promise或者使用第二個callback返回值:

middleware/stats.js

import axios from 'axios' 
export default function ({ route }) {
 return axios.post('http://my-stats-api.com',{
 url: route.fullPath
 })
}

然後,在nuxt.config.js,佈局或者頁面中,配置middleware引數

nuxt.config.js

module.exports = {
 router: {
 middleware: 'stats'
 } 
}

中介軟體stats將在每次路由改變時被呼叫。

想了解中介軟體的例子,請移步example-auth0

以上這篇nuxt 自定義 auth 中介軟體實現令牌的持久化操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。