nuxt custom auth middleware implements token persistence operation
- 2021-09-12 00:23:23
- OfStack
The core point is that under process. server, the data previously stored in cookie is reused under store. commit1
auth.js
/* eslint-disable no-unused-vars */
/* eslint-disable no-useless-return */
export const TokenKey = 'Admin-token'
/**
* Parse what the server gets 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])
}
}
// Login page
const loginPath = '/login'
// Home page
const indexPath = '/home'
// Routing whitelist, directly bypassing routing guards
const whiteList = [loginPath]
/**
* @description Authentication middleware for verifying login
*
*/
export default async ({ store, redirect, env, route, req }) => {
const { path, fullPath, query } = route
const { redirect: redirectPath } = query
// Refresh response vuex Solution of state loss
if (process.server) {
const cookie = req.headers.cookie
const token = getCookie(cookie, TokenKey)
// Setting login status
if (token) {
store.commit('LOGIN', token) //'LOGIN' And store In mutations Just correspond to it
}
if (token) {
// Has logged in, the login page comes in, and there is a redirected path, so jump to the redirected path directly
if (path === loginPath && path !== redirectPath) {
redirect(redirectPath)
} else if (path === '/') {
redirect(indexPath)
} else {
// Others have been logged in and skipped directly
return
}
} else {
// Authentication white list
if (whiteList.includes(path)) return
// Not logged in, not the login page comes in, all redirect to the login page
if (!path.includes(loginPath)) {
redirect(`${loginPath}?redirect=${encodeURIComponent(fullPath)}`)
}
}
}
}
Additional knowledge: NUXT middleware Middleware
Middleware enables your custom functions to run before rendering the page
All middleware must be placed in the middleware/directory. The filename will be the middleware name (for example, middleware/auth will be the middleware auth).
The middleware receives the context as the first parameter:
export default function (context) {
context.userAgent = context.isServer ? context.req.headers['user-agent'] : navigator.userAgent
}
Middleware will execute in sequence in this order:
1. nuxt. config. js
2. Matched layout
3. Matching pages
The middleware can be asynchronous, returning only one Promise or using a second callback return value:
middleware/stats.js
import axios from 'axios'
export default function ({ route }) {
return axios.post('http://my-stats-api.com', {
url: route.fullPath
})
}
Then, in nuxt. config. js, layout, or page, configure the middleware parameters
nuxt.config.js
module.exports = {
router: {
middleware: 'stats'
}
}
The middleware stats will be called every time the route changes.
For an example of middleware, go to example-auth0