2.0.1 • Published 5 years ago

egg-token v2.0.1

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

egg-token

Egg.js middleware that uses encrypted token to authenticate.

License Version codecov TravisCI

Install

npm i egg-token
# or
yarn add egg-token

Usage

// {app_root}/config/plugin.js
exports.token = {
  enable: true,
  package: 'egg-token'
};

Configuration

// {app_root}/config/config.default.js
exports.middleware = ['token'];

exports.token = {
  type: 'md5',

  apps: {
    felixpy: {
      secret: 'XnMib79vzwP01gtr',
      expires: 30000
    },
    codetrial: {
      secret: 'mi9yNGT6zwrqMv8z',
      expires: 30000
    }
  }
};

type is the algorithm that can be used to generate hash digests.

See crypto.createHash for more detail.

Each key of apps is the application's code, secret is used to generate token and expires is the validity period of the token.

The way to generate tokens is as follows:

const ts = Date.now();
const md5Value = md5(`${APP_CODE}:${ts}:${APP_SECRET}`);
const token = base64Encode(`${APP_CODE}:${ts}:${md5Value}`);

Example

This is an example of using axios to request an api:

const crypto = require('crypto');
const axios = require('axios');

const hash = crypto.createHash('md5');

const APP_CODE = 'felixpy';
const APP_SECRET = 'XnMib79vzwP01gtr';

const ts = Date.now();
const md5Value = hash.update(`${APP_CODE}:${ts}:${APP_SECRET}`).digest('hex');

const token = Buffer.from(`${APP_CODE}:${ts}:${md5Value}`).toString('base64');

axios.get('/url/to/your/egg/service', {
  headers: {
    'egg-api-token': token
  }
});

License

MIT

Copyright (c) 2018 - present, Felix Yang