Search code examples
node.jsexpresspassport.jspassport-azure-ad

NodeJS Passport configured per route, added as middleware and getting no errors but it does not work/fire


I have a NodeJS Api and I authenticate with Passport Azure AD Bearer Token -- all is fine when I configure this globally but in order to be able to keep it clean I need to configure it per route file.

I have taken the logic on the front page and just added it inside the route file as middleware but it does not seem to fire:

router.use(function (req, res, next) {
passport.initialize()
passport.use(bearerStrategy);
passport.authenticate('oauth-bearer', { session: false })
next();
})

The config objects are also present above this code.


Solution

  • I ended up renaming my passport config objects and initalization objects with an added _appname for each app and initialized them all in the index.js and then simply mentioning on the parent route which passport instance protects which.

    Code below:

        // MIDDLEWARE    
        app.use(passport_myAppName.initialize());
        passport_myAppName.use(bearerStrategy_myAppName)
    
        app.use(passport_mySecondApp.initialize());
        passport_mySecondApp.use(bearerStrategy_mySecondApp)
    
        // ROUTES
        app.use("/myAppName", passport_idtTV.authenticate('oauth-bearer', { session: false }), myAppName);
        app.use("/mySecondApp", passport_idtTV.authenticate('oauth-bearer', { session: false }), mySecondApp);