Passport - override strategy dynamically

I have a node application with a passport library. I use the passport strategy as follows:

passport.use(someStrategy) 

Is it possible to override this strategy dynamically later? When starting the application, I would like to use a different strategy at some point. Actually the same strategy, but with a different configuration.

If I just make another .use passport (someOtherStrategy), is it not easy to add another middleware to the passport? Then it will not delete the old one, just add another one. I would like the old one to be deleted. Therefore, either override or delete and add a new one.

+5
source share
2 answers

Digging through the source code of the passport showed that redefinition can be done easily. Here is the relevant piece of 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 you can see from the code, if the strategy you are using has a name that is already used by another strategy in the _strategies list, then it is replaced by the new strategy. You can also delete the strategy using the unuse method, as can be seen from the code.

@Mitch. Your answer is helpful, but a little off topic. Probably partly because I was not absolutely sure that I was looking for a way to override the existing strategy, and not just how to set up several strategies. Sorry, I was not very clear in my description of the question.

0
source

You can configure several of these strategies in the passport, even one type. Below I can have two instances of myStrategy with different configurations, but in a different way,

For instance:

 passport.use('someStrategy', new myStrategy(options)) passport.use('anotherStrategy', new myStrategy(differentOptions)); 

Then, after authentication, you can specify which strategy to use:

 passport.authenticate('someStrategy', ...); 

Using the foregoing, you can configure several strategies and, based on a conditional decision, decide which strategy to use:

 if (condition){ passport.authenticate('someStrategy', ...); } else{ passport.authenticate('anotherStrategy', ...); } 

Or:

 let strategyToUse = determineStrategy(); //dynamically choose which strategy you want passport.authenticate(strategyToUse, ...); 

Removing a strategy from the middleware stack is a bit more complicated, and there is no built-in function for this, I don't think. This may require manual splicing of the strategy from the stack. This question may help you remove middleware from the stack; his goal of express communication should also apply to a passport to some extent.

0
source

Source: https://habr.com/ru/post/1271287/


All Articles