Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport - override strategy dynamically

I have a node application with passport library. I use passport strategy like this:

passport.use(someStrategy)

Is it possible to override that strategy later on dynamically? During the application run, I would want to at some point use a different strategy. Actually same strategy, but with a different configuration.

If I just make another passport.use(someOtherStrategy), then doesn't that just add another 'middleware' to passport? Then that wouldn't delete the old one, just add one more. I would want the old one to be deleted. So either override, or delete and add a new one.

like image 437
Ville Miekk-oja Avatar asked Aug 28 '17 07:08

Ville Miekk-oja


People also ask

Can passport use multiple strategies?

Passport's middleware is built in a way that allows you to use multiple strategies in one passport.

What are Passportjs strategies?

Strategies are responsible for authenticating requests, which they accomplish by implementing an authentication mechanism. Authentication mechanisms define how to encode a credential, such as a password or an assertion from an identity provider (IdP), in a request.

Does passport use session?

Passport uses serializeUser function to persist user data (after successful authentication) into session. The function deserializeUser is used to retrieve user data from session and perform some condition-based operations. Now all the endpoints hitting the backend server will go through passport.

What is passport local strategy?

passport-local is the strategy you would use if you are authenticating against a username and password stored 'locally' i.e. in the database of your app - 'local' means local to your application server, not local to the end user. passport-jwt is the strategy for using JSON Web Tokens.


1 Answers

Digging in passport source code revealed that overriding can be done easily. Here is the relevant part of the code:

Authenticator.prototype.use = function(name, strategy) {
  if (!strategy) {
    strategy = name;
    name = strategy.name;
  }
  if (!name) { throw new Error('Authentication strategies must have a name'); }

  this._strategies[name] = strategy;
  return this;
};
...
...
Authenticator.prototype.unuse = function(name) {
  delete this._strategies[name];
  return this;
};

As can be seen from the code, if the strategy that you use has a name that is already used by another strategy in the _strategies list, then it is replaced by the new strategy. Also one can delete the strategy with method unuse, as seen in the code also.

@Mitch Your answer is helpfull, but little off-topic. Probably partly because I was not super clear that I was searching for a way to override an existing strategy, not just how to configure multiple strategies. Sorry, I wasn't super clear in my question description.

like image 187
Ville Miekk-oja Avatar answered Sep 22 '22 23:09

Ville Miekk-oja