apigee-127/swagger-tools

middleware swaggerSecurity unable to access res object

Opened this issue · 1 comments

Hello,

I am trying to process token and send a response back if the token is not present. I am trying to follow the document here

The issue is that in the auth code, I am unable to access req.res object to overload the response.

// Line 15 on verifyToken code in the link above
function sendError() {
        return req.res.status(403).json({message: 'Error: Access Denied'});
    }

Here is how I am initializing the middleware.

// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {
  
    // Route validated requests to appropriate controller
    app.use(middleware.swaggerRouter(options));
    
  // Serve the Swagger documents and Swagger UI
  app.use(middleware.swaggerUi());

  // Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
  app.use(middleware.swaggerMetadata());

  // Validate Swagger requests
  app.use(middleware.swaggerValidator());

  // Use security
  app.use(middleware.swaggerSecurity({
    Bearer: auth.verifyToken
  }));

Appreciate any pointers.

  • S

Late to this, but for anybody who finds it... you need to include a call to OPs proposed error handler:

app.use(sendError)

at the end of your Express.js chain inside of your swagger initialization code.

the sendError function should have parameters of req, res, err, next

function sendError(req, res, err, next) { return res.status(403).json({message: 'Error: Access Denied'}); }

This works because an invalid token throws an error from its callback... i.e. (on Swagger 2.0):

function initializeSwaggerSecurity(middleware) { return middleware.swaggerSecurity({ jwtAuth: (req, authOrSecDef, scopes, callback) => { passport.authenticate('jwt', {session: false}, (err, user, info) => { if (err) { return callback(new Error(CONSTANTS.AUTHENTICATION.ERROR_MESSAGE_DEFAULT)) }; if (!user) { return callback(new Error(CONSTANTS.AUTHENTICATION.ERROR_MESSAGE_TOKEN)) } else { req.user = user; return callback(); } })(req, null, callback); } }); };

Lastly, if the response is just not there for you to work with (i.e. couldn't find res.status), I just composed a new response using a util tool I have and returned that.