This time I will bring you how to use Koa and Session for routing authentication in the nuxt framework. What are the precautions for using Koa and Session for routing authentication in the nuxt framework? , the following is a practical case, let’s take a look.
Introduction
The backend management page of the blog requires a login system, so consider doing routing authentication. The implementation method is also given by the Nuxt official website. Chestnut was rewritten, and the front-end and back-end routing were also unified.Route interception
The front-end mainly uses Nuxt’smiddleware to do route interception. Vuex is also required here. State tree is used to do it.
middleware
middleware/auth.jsexport default function ({ store, redirect }) { if (!store.state.user) { return redirect('/login') } }
export default { middleware: 'auth', components: { AdminAside } }
page layout of the background management system
nuxtServerInit
In the rendering process of NuxtJs, when a request comes in, the nuxtServerInit method is called first. This method can be used to save the server's data in advance. We can use this method to receive Session information that stores user information.nuxtServerInit ({ commit }, { req, res }) { if (req.session && req.session.user) { const { username, password } = req.session.user const user = { username, password } commit('SET_USER', user) } },
Using Koa and koa-session
Koa and koa-session
The back-end code I use is the Koa framework, and koa- session to process the Session. When creating a new nuxt project, you can directly choose the Koa framework.vue init nuxt/koa
npm install koa-session
import Koa from 'koa' import { Nuxt, Builder } from 'nuxt' // after end import session from 'koa-session' async function start () { const app = new Koa() const host = process.env.HOST || '127.0.0.1' const port = process.env.PORT || 7998 // Import and Set Nuxt.js options let config = require('../nuxt.config.js') config.dev = !(app.env === 'production') // Instantiate nuxt.js const nuxt = new Nuxt(config) // Build in development if (config.dev) { const builder = new Builder(nuxt) await builder.build() } // body-parser app.use(bodyParser()) // mongodb // session app.keys = ['some session'] const CONFIG = { key: 'SESSION', /** (string) cookie key (default is koa:sess) */ /** (number || 'session') maxAge in ms (default is 1 days) */ /** 'session' will result in a cookie that expires when session/browser is closed */ /** Warning: If a session cookie is stolen, this cookie will never expire */ maxAge: 86400000, overwrite: true, /** (boolean) can overwrite or not (default true) */ httpOnly: true, /** (boolean) httpOnly or not (default true) */ signed: true, /** (boolean) signed or not (default true) */ rolling: false /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. default is false **/ } app.use(session(CONFIG, app)) // routes app.use(async (ctx, next) => { await next() ctx.status = 200 // koa defaults to 404 when it sees that status is unset return new Promise((resolve, reject) => { ctx.res.on('close', resolve) ctx.res.on('finish', resolve) nuxt.render(ctx.req, ctx.res, promise => { // nuxt.render passes a rejected promise into callback on error. promise.then(resolve).catch(reject) }) }) }) app.listen(port, host) console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console } start()
Login routing
// 登录 router.post('/api/login', async (ctx, next) => { const { username, password } = ctx.request.body let user, match try { user = await Admin.findOne({ user: username }).exec() if (user) { match = await user.comparePassword(password, user.password) } } catch (e) { throw new Error(e) } if (match) { ctx.session.user = { _id: user._id, username: user.user, nickname: user.nickname, role: user.role } console.log(ctx.session) return (ctx.body = { success: true, data: { username: user.user, nickname: user.nickname } }) } return (ctx.body = { success: false, err: '密码错误' }) })
session is not defined
ProblemnuxtServerInit ({ commit }, { req, res }) { if (req.session && req.session.user) { // res.session is not defined const { username, password } = req.session.user const user = { username, password } commit('SET_USER', user) } }
Reason
The final problem is still due to my carelessness and neglect of some details. Among the chestnuts given on the official website:app.post('/api/login', function (req, res) { if (req.body.username === 'demo' && req.body.password === 'demo') { req.session.authUser = { username: 'demo' } return res.json({ username: 'demo' }) } res.status(401).json({ error: 'Bad credentials' }) })
Solution
So when injecting nuxt.render, add session to requestapp.use(async (ctx, next) => { await next() ctx.status = 200 // koa defaults to 404 when it sees that status is unset ctx.req.session = ctx.session return new Promise((resolve, reject) => { ctx.res.on('close', resolve) ctx.res.on('finish', resolve) nuxt.render(ctx.req, ctx.res, promise => { // nuxt.render passes a rejected promise into callback on error. promise.then(resolve).catch(reject) }) }) })
detailed explanation of the steps to implement fuzzy query with jQuery
detailed explanation of node Async/Await asynchronous programming implementation
The above is the detailed content of How to use Koa and Session for routing authentication in nuxt framework. For more information, please follow other related articles on the PHP Chinese website!