Skip to content
This repository has been archived by the owner on Aug 4, 2023. It is now read-only.

middleware swaggerSecurity unable to access res object #618

Open
ctippur opened this issue Apr 15, 2020 · 1 comment
Open

middleware swaggerSecurity unable to access res object #618

ctippur opened this issue Apr 15, 2020 · 1 comment

Comments

@ctippur
Copy link

ctippur commented Apr 15, 2020

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
@epiphanizer
Copy link

epiphanizer commented Jun 2, 2022

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants