node.jskoanode-oidc-provider

How to validate request body before the client registration in node-oidc-provider?


I'm trying to code a validation to be executed on node-oidc-provider that needs to read the request body before process the DCR.

I'm using the example provider like below:

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');
});

Inside the ctx there's a req attribute but without the body exposed, so to extract it I have create the following function:

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

The problem is that if I use this function to get the request body and execute my validation the "await next()" will try to do the same and will fail.

So, how to make this validation without impact the next function that will be called?


Solution

  • I've found a way. I just added the dependency koa-bodyparser and now I have access to the request body using 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');
    });