Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport-js How to create a custom strategy

Tags:

I am looking to create my own strategy.

I have client_id, client_secret and related meta data. I also know the flow of execution. So I want to create my own strategy and add my custom logic for authentication.

I looked at passport-strategy, but I am not understanding how to implement my own strategy. Can anyone explain it?

like image 957
Sam Avatar asked May 31 '17 06:05

Sam


1 Answers

You have two options here:

If you have a custom logic for authentication you don't really need to create your own strategy... you can use the passport-custom strategy which allows you to build this logic. According to the documentation:

The custom authentication strategy authenticates users by custom logic of your choosing

Unless you want to actually build a strategy that you want to distribute (eg: an implementation of OpenID or something like that), I don't see the point on implementing your own strategy.

However, implementing your own strategy consists in implementing the passport-strategy abstract class. I'd suggest to look into the Github page instead of the npm page as it has more information about how to get up and running. Basically, the steps to follow to have your own strategy is:

  1. Subclass Strategy
  2. Implement Authentication by defining the authenticate() method on the prototype (here you'll have your custom logic).
  3. Invoke one of the Augmented Methods (.success, .fail, .pass, .redirect or .error)

Finally you would need to pack it as an npm module and once you have everything in place you can go and require your own strategy in your Node.js project.

As I said, I think that you need to have a good reason to go for your own strategy. I'd give a try to the passport-custom.

like image 136
javierfdezg Avatar answered Sep 22 '22 18:09

javierfdezg