Azard / egg-oauth2-server

:star2: OAuth2 server plugin for egg.js based on node-oauth2-server
MIT License
179 stars 45 forks source link

How to use authenticate() as global middleware? #54

Open axolo opened 4 years ago

axolo commented 4 years ago

when use egg-oauth2-server plugin as global middleware:

// app/middleware/auth.js

module.exports = options => {
  return async (ctx, next) => {
    try {
      const auth = await ctx.app.oAuth2Server.authenticate();
      console.log(auth); 
      await next();
    } catch (err) {
      ctx.logger.error(err);
    }
  };
};
// config/config.default.js

config.middleware = [ 'auth' ];

then output: [AsyncFunction]

when use authenticate() in egg controller:

// app/controller/debug.js

async index() {
  const { app, ctx } = this;
  const res = await app.oAuth2Server.authenticate();
  ctx.body = res;
}

then throw:

{
  "code": "ERR_INVALID_ARG_TYPE",
  "message": "The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. Received type undefined",
  "stack": "TypeError [ERR_INVALID_ARG_TYPE]: The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. Received type undefined\n    at Function.byteLength (buffer.js:494:11)\n    at respond (D:\\Develop\\projects\\zhifu\\api2\\node_modules\\koa\\lib\\application.js:245:25)\n    at handleResponse (D:\\Develop\\projects\\zhifu\\api2\\node_modules\\koa\\lib\\application.js:149:34)\n    at processTicksAndRejections (internal/process/task_queues.js:85:5)",
  "name": "TypeError",
  "status": 500
}