arden / egg-jwt-auth

JWT authentication plugin for egg

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

egg-jwt

NPM version build status Test coverage David deps Known Vulnerabilities npm download

Egg's JWT(JSON Web Token Authentication Plugin)

Install

$ npm i egg-jwt --save

or

yarn add egg-jwt

Usage

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

Configuration

// {app_root}/config/config.default.js
exports.secret = '123456'

see config/config.default.js for more detail.

Example

// app/router.js
'use strict';

module.exports = app => {
  app.get('/', app.jwt, 'render.index');
  app.get('/login', 'login.index');
  app.get('/success', app.jwt, 'success.index');
};

// app/controller/render.js
'use strict';

module.exports = app => {
  class RenderController extends app.Controller {
    * index() {
      this.ctx.body = 'hello World';
    }
  }
  return RenderController;
};

// app/controller/login.js
'use strict';

module.exports = app => {
  class LoginController extends app.Controller {
    * index() {
      this.ctx.body = 'hello admin';
    }
  }
  return LoginController;
};

// app/controller/success.js
'use strict';

module.exports = app => {
  class SuccessController extends app.Controller {
    * index() {
      this.ctx.body = this.ctx.state.user;
    }
  }
  return SuccessController;
};

Then

curl 127.0.0.1:7001
// response 401

curl 127.0.0.1:7001/login
// response hello admin

curl -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmb28iOiJiYXIiLCJpYXQiOjE0OTAwMTU0MTN9.ehQ38YsRlM8hDpUMKYq1rHt-YjBPSU11dFm0NOroPEg" 127.0.0.1:7001/success
// response {foo: bar}

How To Create A Token

const token = app.jwt.sign({ foo: 'bar' }, app.config.jwt.secret);

Questions & Suggestions

Please open an issue here.

License

MIT

About

JWT authentication plugin for egg

License:MIT License


Languages

Language:JavaScript 92.0%Language:Shell 8.0%