如何在node-oidc-provider中进行客户端注册之前验证请求体?

qzwqbdag  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(260)

我正在尝试编写一个在node-oidc-provider上执行的验证,它需要在处理DCR之前读取请求体。
我使用的示例提供程序如下所示:

import Provider from 'oidc-provider';
import { configuration } from './configuration.js';

const provider = new Provider('http://localhost:3000', configuration);

provider.use(async (ctx, next) => {
    // pre-processing
    if (ctx.path == "/reg") {
      console.log("DCR was called...")
      //Validations here
    }

    await next();
    
    //post-processing
    console.log('post middleware', ctx.method, ctx.oidc.route);
});

provider.listen(3000, () => {
  console.log('oidc-provider listening on port 3000, check http://localhost:3000/.well-known/openid-configuration');
});

在ctx内部有一个req属性,但没有暴露主体,因此为了提取它,我创建了以下函数:

export const getRequestBody = async function (req) {
  return new Promise((resolve, reject) => { 
    let requestBody = '';

    req.on('data', (chunk) => {
      requestBody += chunk;
    });

    req.on('end', () => {
      resolve(requestBody);
    });

    req.on('error', (error) => {
      reject(error);
    });
  });
};

问题是,如果我使用这个函数来获取请求体并执行我的验证,“await next()”将尝试做同样的事情,并且会失败。
那么,如何在不影响下一个将被调用的函数的情况下进行验证呢?

js4nwp54

js4nwp541#

我找到了一个办法我刚刚添加了依赖项koa-bodyparser,现在我可以使用ctx. request. body访问请求体。

import Provider from 'oidc-provider';
import { configuration } from './configuration.js';
import bodyParser from 'koa-bodyparser';

const provider = new Provider('http://localhost:3000', configuration);

provider.use(bodyParser());
provider.use(async (ctx, next) => {
    // pre-processing
    if (ctx.path == "/reg") {
      console.log("DCR was called...")
      console.log("DCR request body: ", ctx.request.body);
    }

    await next();
    
    //post-processing
    console.log('post middleware', ctx.method, ctx.oidc.route);
});

provider.listen(3000, () => {
  console.log('oidc-provider listening on port 3000, check http://localhost:3000/.well-known/openid-configuration');
});

相关问题