项目作者: Azard

项目描述 :
:star2: OAuth2 server plugin for egg.js based on node-oauth2-server
高级语言: JavaScript
项目地址: git://github.com/Azard/egg-oauth2-server.git
创建时间: 2017-04-25T17:55:25Z
项目社区:https://github.com/Azard/egg-oauth2-server

开源协议:MIT License

下载


egg-oauth2-server

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

Chinese Example | 中文样例教程(注意:文章里使用的是该插件 v1.x 版本,部分 API 名称有变化,主要流程一致)

egg-oauth2-server is a module that easily adds oauth2 capability to egg-based servers.

  • egg 2.x use egg-oauth2-server latest (Node >= 8.0.0)
  • egg 1.x use egg-oauth2-server 2.0.x (Node >= 6.0.0)

Install

  1. $ npm i egg-oauth2-server --save

Usage

  1. // {app_root}/config/plugin.js
  2. exports.oAuth2Server = {
  3. enable: true,
  4. package: 'egg-oauth2-server',
  5. };
  6. // {app_root}/app/router.js
  7. app.all('/user/token', app.oAuth2Server.token());
  8. app.get('/user/authorize', app.oAuth2Server.authorize(), 'user.code');
  9. app.get('/user/authenticate', app.oAuth2Server.authenticate(), 'user.authenticate');
  10. // `ctx.state.oauth` has token or code data after middleware for controller.
  1. // {app_root}/config/config.default.js
  2. module.exports = config => {
  3. const exports = {};
  4. exports.oAuth2Server = {
  5. debug: config.env === 'local',
  6. grants: [ 'password' ],
  7. };
  8. return exports;
  9. };

See test/fixtures/apps/oauth2-server-test/config/config.unittest.js for reference.

  1. // {app_root}/app/extend/oauth.js
  2. // or {app_root}/app/extend/oauth.ts
  3. 'use strict';
  4. // need implement some follow functions
  5. module.exports = app => {
  6. class Model {
  7. constructor(ctx) {}
  8. async getClient(clientId, clientSecret) {}
  9. async getUser(username, password) {}
  10. async saveAuthorizationCode(code, client, user) {}
  11. async getAuthorizationCode(authorizationCode) {}
  12. async revokeAuthorizationCode(code) {}
  13. async saveToken(token, client, user) {}
  14. async getAccessToken(bearerToken) {}
  15. async revokeToken(token) {}
  16. }
  17. return Model;
  18. };

For full description, check out https://www.npmjs.com/package/oauth2-server.

Examples

A simple password-mode OAuth 2.0 server. Full code at test/fixtures/apps/oauth2-server-test/app/extend/oauth.js

password mode app.oauth.token() lifecycle

getClient —> getUser —> saveToken

password mode app.oauth.authenticate() lifecycle

Only getAccessToken

authorization_code mode app.oauth.authorize() lifecycle

getClient —> getUser —> saveAuthorizationCode

authorization_code mode app.oauth.token() lifecycle

getClient —> getAuthorizationCode —> revokeAuthorizationCode —> saveToken

authorization_code mode app.oauth.authenticate() lifecycle

Only getAccessToken

Questions & Suggestions

Please open an issue. PRs are welcomed too.

License

MIT