Skip to content
JWT authentication plugin for egg
JavaScript
Branch: master
Clone or download
Latest commit 22400fe Nov 19, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
app
config feat: koa-jwt 改為 middleware 形式 (#7) Jun 26, 2017
test fix: jwt sign and verify should support callback Aug 26, 2018
.autod.conf.js
.eslintignore first commit Sep 30, 2016
.eslintrc
.gitignore feat: optional push jwt after cors in coreMiddleware Jan 16, 2018
.npmignore first commit Sep 30, 2016
.travis.yml feat: remove yarn.lock Nov 19, 2019
History.md
LICENSE update egg core dep; add README;update test code Mar 20, 2017
README.md feat: use koa-jwt2 Mar 13, 2018
README.zh_CN.md
app.js feat: jwt verify and sign assign from config (#24) Jul 24, 2018
appveyor.yml feat: remove yarn.lock Nov 19, 2019
index.d.ts
package.json Release 3.1.7 Nov 19, 2019

README.md

egg-jwt

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

Egg's JWT(JSON Web Token Authentication Plugin)

Important

egg-jwt@3 use koa-jwt2

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.jwt = {
  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"); // use old api app.jwt
  app.get("/login", "login.index");
  app.get("/success", "success.index"); // is setting in config.jwt.match
};

// 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);

For more options, check here

Questions & Suggestions

Please open an issue here.

License

MIT

You can’t perform that action at this time.