Passport-js How to create a custom strategy

蓝咒 提交于 2019-12-10 12:31:19

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/44277756/passport-js-how-to-create-a-custom-strategy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!