directory

  1. Egg gracefully implements exception handling
  2. Egg implements JWT authentication

preface

JWT (JSON Web Token) authentication JWT is an open standard (RFC7519). The details are not repeated here, but you can check out the documentation. Here is a brief description of the application in Egg.

Recommended reading: Nguyen Yifeng’s introduction to JWT

Implement middleware yourself

Let’s start by explaining how to implement middleware ourselves to accomplish JWT authentication

  1. To implement authentication middleware, start by creating a customAuth.js file in the Egg Project Middleware directory from the previous article (here we assume the secret string as the secret key) to retrieve the Autorization field from the Request header. Extract the key string according to JWT definition using verify method and verification
const jsonwebtoken = require('jsonwebtoken');

module.exports = options= > {
  return async(ctx, next) => {
    const { authorization = ' ' } = ctx.request.header;
    const token = authorization.replace('Bearer '.' ');
    try {
      const user = jsonwebtoken.verify(token, 'secret');
      ctx.state.user = user;
    } catch (err) {
      ctx.throw(401, err.message);
    }
      awaitnext(); }}Copy the code
  1. Implement login signature interface and test interface
// router.js
'use strict';

/** * @param {Egg.Application} app - egg application */
module.exports = app= > {
  const auth = app.middleware.customAuth();
  const { router, controller } = app;
  router.get('/', controller.home.index);
  router.get('/login', controller.home.login);
  router.get('/testlogin', auth, controller.home.needLogin);
};
Copy the code
// controller/home.js
'use strict';
const jsonwebtoken = require('jsonwebtoken');
const Controller = require('egg').Controller;

class HomeController extends Controller {
  The // login interface is used for signing. In normal cases, this interface verifies the user name and password. In this case, Demo directly invokes the sign method to sign and sets the expiration time to one day
  async login() {
    const { ctx } = this;
    const secret = 'secert';
    const token = jsonwebtoken.sign({ key: 'value' }, secret, { expiresIn: '1d' });
    ctx.body = { token };
  }

  // Test authentication
  async needLogin() {
    const { ctx } = this;
    ctx.body = 'This is the data returned by the validated interface.'; }}module.exports = HomeController;
Copy the code

test

To test the CSRF plugin, add the following code to the config.default.js file to temporarily disable the Cross-site Request Forgery.

  config.security = {
    enable: false,},Copy the code

Postman invokes the login interface

Postman invokes the interface that requires authentication The JWT authentication mode of Postman is used. The same token is obtained from global variables

Avoid reinventing the wheel

Use the existing KOA-JWT for authentication. The previous article explained how to reference the KOA middleware, so we now create auth.js under middleware

module.exports = require('koa-jwt');
Copy the code

Modify middleware references in router.js

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const auth = app.middleware.auth({ secret: 'secret' });
  const { router, controller } = app;
  router.get('/', controller.home.index);
  router.get('/login', controller.home.login);
  router.get('/testlogin', auth, controller.home.needLogin);
};

Copy the code

After the test, can still get the same effect as the above written; Here, KOA-JWT simplifies our code and implements the same functionality as our own middleware verify