Home > Web Front-end > JS Tutorial > body text

How to use Koa and Session for routing authentication in nuxt framework

php中世界最好的语言
Release: 2018-05-22 14:06:01
Original
1882 people have browsed it

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’s

middleware to do route interception. Vuex is also required here. State tree is used to do it.

middleware

middleware/auth.js

export default function ({ store, redirect }) {
 if (!store.state.user) {
  return redirect('/login')
 }
}
Copy after login
Re-authenticate the page by verifying whether the user information on the status tree exists. Orientation

layouts/admin.vue

export default {
  middleware: 'auth',
  components: {
   AdminAside
  }
 }
Copy after login
Add middleware on the

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)
  }
 },
Copy after login
When the application is completed, some data we obtained from the server will be filled in this state tree (store).

According to the examples given on the NuxtJs official website, we have basically finished writing the routing authentication part of the page. The next step is to write the code for this part of the server side

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
Copy after login
Related dependencies

npm install koa-session
Copy after login
Rewrite in server.js

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()
Copy after login
For koa- For the usage of session, you can refer to: Learning cookie and session from koa-session middleware

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: '密码错误'
 })
})
Copy after login
Written here, the entire function The process is basically completed and very smooth, but for me there is no such thing as smooth sailing code.

session is not defined

Problem

nuxtServerInit ({ 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)
  }
 }
Copy after login
No information about the session can be obtained in nuxtServerInit, but other APIs can obtain the session. At that time, because I couldn't find the reason, I once suspected that there was something wrong with the chestnuts. .

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' })
})
Copy after login
It will The session is saved in req.session, so the session in nuxtServerInit does exist in req.session. However, I use Koa2 and Koa-session. Koa-session parses the cookie to ctx.session, which does not exist in req.session.

Solution

So when injecting nuxt.render, add session to request

app.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)
   })
  })
 })
Copy after login
I believe you have mastered it after reading the case in this article For more exciting methods, please pay attention to other related articles on the php Chinese website!

Recommended reading:

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!