Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – Passport策略如何在场景后面工作大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图了解护照策略是如何运作的.

考虑我用于验证的这些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相关联?或者护照如何在幕后知道谷歌策略的位置**

另外,在我们通过护照完成后,确认一下.它去序列化?

解决方法

当您需要护照时,您会得到一个单身实例,即它是在您第一次需要护照时构建的,并且每次随后都需要重复使用.

因此,您无需在模块之间共享实例,即无需导出.您在实例上执行的任何配置都可在您需要的任何位置看到.

NodeJS中的其他对象以相同的方式工作,一个突出的例子是快速应用程序实例.

这是护照的source code,你可以验证这一点.

大佬总结

以上是大佬教程为你收集整理的node.js – Passport策略如何在场景后面工作全部内容,希望文章能够帮你解决node.js – Passport策略如何在场景后面工作所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: