Koa use Json Web Token (JWT) solutions

1. dependence

  • jsonwebtoken for issuing, parsing token
  • koa-jwt route for access control
  • koa-bodyparser for parsing data post

2. Create a simple Token acquisition and verification mechanism

2.1 acquire Token

Introducing jsonwebtoken library, a token may be generated according to information passed json string. localStroage hold the client token may be hosted on the user's browser each time the background to send http request, stored in the Authorization Token Http Headers field, used to communicate with the server as a credential.

Generating a Token following way:

const jwt = require('jsonwebtoken')
const secret = 'secret' // 自定义的加密字符串
function getToken(payload = {}) {
  return jwt.sign(payload, secret, { expiresIn: '4h' })
}

let token = getToken({uid: "12306", username: "EsunR"}) // 将关键信息记录与 Token 内
console.log(token)

2.2 Verify Token

When a client sends a request to carry Token server, the server by parsing the Http Headers field may obtain authorization Token sent by the client. Get the Token, Token server needs to be parsed to obtain user information stored in the Token, it is necessary to decrypt the Token disposed before a good secretkey, Token analytical sample as follows:

const bodyparser = require('koa-bodyparser') // 引入 bodypaser 用于解析 authorization
// 假设以下代码在一个 get 请求中,可以获取上下文对象 ctx
let token = ctx.headers.authorization
// 获取的 Authorization 格式为:Bearer <token>
let payload = jwt.verify(token.split(' ')[1], secret)

Also, if you use koa-jwt, you can directly call ctx.state.userto get the payload content:

let payload = ctx.state.user

3. Route interception

koa-jwtProvides a route to intercept feature, users have the Token and Token not have permission to access the interface is not the same. For example, the user is not logged in can only access /loginand /registerinterface, and then log in to access addresses of other interfaces, we have to add the following middleware match before routing:

/* 路由权限控制 */
app.use(jwtKoa({ secret: secret }).unless({
  // 设置login、register接口,可以不需要认证访问
  path: [
    /^\/api\/login/,
    /^\/api\/register/,
    /^((?!\/api).)*$/   // 设置除了私有接口外的其它资源,可以不需要认证访问
  ]
}));

If an error occurs in this step to check, that is, when a request but does not need to carry when carrying Token will suspend all middleware after the execution, but can be set passthrough: trueto disable this feature

4. Token unified examination

koa-jwtWe can only help if the current set of requests need to carry Token, but does not check the validity of the current Token. So if we are going to design a login module, you need to test the effectiveness of each Token. Then we add a multi-middleware tokenCheck, in koa-jwtcalling after so koa-jwtresponsible for checking whether the request carries Token, which tokenCheckis responsible for checking the validity of the Token:

// server.js
const tokenCheck = require('./tokenCheck')

/* 路由权限控制 */
app.use(jwtKoa({ secret: secret }).unless({
  // 设置login、register接口,可以不需要认证访问
  path: [
    /^\/api\/login/,
    /^\/api\/register/,
    /^((?!\/api).)*$/   // 设置除了私有接口外的其它资源,可以不需要认证访问
  ]
}));

app.use(tokenCheck())
// tokenCheck.js
const tokenCheck = function () {
  return async function (ctx, next) {
    if (ctx.state.user) {
      // 如果携带有效 Token 就对 Token 进行检查(由 kow-jwt 检查 Token 有效性)
      let result = true
      // check here
      if (result) {
        await next()
      } else {
        ctx.body = {
          msg: "Token 检查未通过"
        }
      }
    } else {
      // 如果没有携带 Token 就跳过检查
      await next()
    }
  }
}

module.exports = tokenCheck
Published 48 original articles · won praise 28 · views 40000 +

Guess you like

Origin blog.csdn.net/u012925833/article/details/101109904