mattts
mattts

Reputation: 352

Passportjs multiple authentication strategies external file with expressjs

First off if I am asking a obviously stupid question I apologies in advance.

I have a passport authentication strategy setup currently and it is working ok. The implementation is as follows.

Authentication strategy (authentication.js) :

const passport = require("passport");
const passportJWT = require("passport-jwt");
const params = {
    //Params here
};


module.exports = function LocalStrategy() {
let strategy = new Strategy(params, function (payload, done) {
    //Logic here
});
passport.use(strategy);
return {
    initialize: function () {
        return passport.initialize();
    },
    authenticate: function () {
        return passport.authenticate("jwt", {
            session: false
        });
    }
  };
};

Using in a route :

const localAuth = require('./authentication/LocalStrategy')();

app.get('/test', localAuth.authenticate(), (req, res) => {
    res.json(req.isAuthenticated());
});

In the server.js file

const localAuth = require('./authentication/LocalStrategy')();
app.use(localAuth.initialize());

I am planning to use multiple authentication strategies in a single route and I found this implementation. But rather than having the authentication strategy written in the same server.js I want to have the strategy written in an external file (in my case authentication.js) and refer the strategy in the route as

passport.authenticate(['SOME_OTHER_STRATEGY', 'jwt']

How can I implement this?

Upvotes: 0

Views: 1780

Answers (1)

mattts
mattts

Reputation: 352

Ok apparently I was't trying hard enough, I didn't have to do any change to my current logic other than serializeUser and deserializeUser. and just use:

passport.authenticate(['SOME_OTHER_STRATEGY', 'jwt']) 

that't it.

Upvotes: 1

Related Questions