【问题标题】:How Passport Strategy works behind the Scene护照策略如何在幕后运作
【发布时间】:2019-05-09 18:23:01
【问题描述】:

我试图了解护照策略的工作原理。

考虑一下我用来进行身份验证的这些 api 路由。

  router.get("/google",  passport.authenticate('google', { scope: ['profile', 'email'] }));
  router.get("/google/callback", passport.authenticate('google'), (req, res) => {
      res.redirect("http://localhost:3000/")
  })

这就是护照策略

const passport = require('passport')
const GoogleStratergy = require('passport-google-oauth20')
const keys = require("./key.js")
const User = require("../models/user-model.js")

passport.serializeUser((user, done) => {
    done(null, user.id) 
})

passport.deserializeUser((id, done) => {
    User.findById(id).then((user) => {
        done(null, user) //pass it in req of our routes
    })
})

passport.use(
    new GoogleStratergy({
    //Options for the stratergy 
        callbackURL: "/auth/google/callback", 
        clientID: keys.google.clientID,
        clientSecret: keys.google.clientSecret
    }, (accessToken, refreshToken, profile, done) => {


        User.findOne({userId: profile.id }).then((currentUser) => {
            if (currentUser) {
                done(null, currentUser)
            } else {
                    //Changing Image String
                    let  oldURL=  profile.photos[0]["value"]
                    let newURL =  oldURL.substr(0,  oldURL.length-2);
                    newURL = newURL + "250"
                //Creating Mongoose Database
                    new User({
                        username: profile.displayName,
                        userId: profile.id,
                        image: newURL,
                        email: profile.emails[0]["value"]
                    }).save().then((newUser) => {
                        console.log("new user created", newUser)
                        done(null, newUser)
                   })
            }

        })

    })
)

现在,我想我明白这里发生了什么,但我无法理解的一件事是......

怎么样

passport.use(
    new GoogleStratergy({
    //Options for the stratergy 

被叫到这里?我的意思是我没有看到任何导出语句,那么它如何与 Node App 链接?或者passport怎么在幕后知道我们google策略的位置**

另外,只是为了确认一下,在我们通过护照完成后。使用?它要序列化吗?

【问题讨论】:

    标签: node.js passport.js


    【解决方案1】:

    当你requirepassport 时,你会得到一个单例实例,即它是在你第一次requirepassport 时构建的,并且在随后的required 每次和任何地方都被重用。

    因此您不需要在模块之间共享实例,即不需要导出。您在实例上所做的任何配置在您需要的任何地方都可见。

    NodeJS 中还有其他以相同方式工作的对象,一个突出的例子是express 应用程序实例。

    这是护照的source code,您可以在此验证。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-12
      • 1970-01-01
      • 2012-06-09
      • 2021-06-20
      • 2015-03-20
      • 2021-02-11
      • 2021-09-02
      • 1970-01-01
      相关资源
      最近更新 更多