Project warehouse

Github.com/XingGuoZM/e…

The development environment

MAC 10.14.2 node v10.16.3Copy the code

Step 1: Make sure the project runs

mkdir egg-jwtTest && cd egg-jwtTest
npm init egg --type=simple
npm install
npm run dev
Copy the code

Step 2: Install dependency packages

Installing a plug-in

npm install --save egg-cors egg-jwt
Copy the code

Directory as follows

Step 3: Complete the function and generate the token

config/config.default.js

/* eslint valid-jsdoc: "off" */

'use strict';

/ * * *@param {Egg.EggAppInfo} appInfo app info
 */
module.exports = appInfo= > {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}* * /
  const config = exports = {};

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1576461360545_5788';

  // add your middleware config here
  config.middleware = [];
  config.jwt = {
    secret: '123456'};// Security configuration (https://eggjs.org/zh-cn/core/security.html)
  config.security = {
    csrf: {
      enable: false.ignoreJSON: true,},// Whitelist of the interfaces that are allowed to access
    domainWhiteList: [ 'http://localhost:8080']};// Cross-domain configuration
  config.cors = {
    origin: The '*'.allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'};// add your user config here
  const userConfig = {
    // myAppName: 'egg',
  };

  return{... config, ... userConfig, }; };Copy the code

config/plugin.js

'use strict';

/ * *@type Egg.EggPlugin */
module.exports = {
  jwt: {
    enable: true.package: 'egg-jwt',},cors: {
    enable: true.package: 'egg-cors',}};Copy the code

app/controller/user.js

'use strict';

const Controller = require('egg').Controller;


class UserController extends Controller {
  / / login
  async login() {
    const { ctx, app } = this;
    const data = ctx.request.body;
    const token = app.jwt.sign({
      nickname: data.nickname,
    }, app.config.jwt.secret);
    ctx.body = token;
  }
  // Verify token, configure Authorization= 'Bearer ${token}' in header when requesting
  // Special note: The token cannot be sent directly, but must be preceded by a Bearer string and a space
  async index() {
    const { ctx } = this;
    console.log(ctx.state.user);
    ctx.body = { code: 201.msg: 'Validation successful'}; }}module.exports = UserController
;
Copy the code

app/router.js

'use strict';

/ * * *@param {Egg.Application} app - egg application
 */
module.exports = app= > {
  const { router, controller, jwt } = app;
  router.get('/', controller.home.index);

  router.post('/user/login', controller.user.login);
  router.post('/user', jwt, controller.user.index);
};
Copy the code

Step 4: Test yourself with Postman

reference

  • Getting Started with EggJS series – Use egg-Jwt