Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 内部OAuth错误:无法获取用户配置文件NodeJs+;passport-google-oAuth2_Node.js_Google Authentication_Passport Google Oauth2 - Fatal编程技术网

Node.js 内部OAuth错误:无法获取用户配置文件NodeJs+;passport-google-oAuth2

Node.js 内部OAuth错误:无法获取用户配置文件NodeJs+;passport-google-oAuth2,node.js,google-authentication,passport-google-oauth2,Node.js,Google Authentication,Passport Google Oauth2,我正在学习使用passport-google-oauth20进行身份验证。当我尝试使用Google+注册用户时,在提交请求失败后,我会不断收到此错误消息(InternalOAuthError:failed to fetch user profile) 我尝试了这个解决方案: 我启用了Google+API并等待 2.不推荐的作用域 //jshint esversion:6 require('dotenv').config() const express = require("express");

我正在学习使用passport-google-oauth20进行身份验证。当我尝试使用Google+注册用户时,在提交请求失败后,我会不断收到此错误消息(InternalOAuthError:failed to fetch user profile)

我尝试了这个解决方案:

  • 我启用了Google+API并等待
  • 2.不推荐的作用域

    //jshint esversion:6
    require('dotenv').config()
    const express = require("express");
    const bodyParser = require("body-parser");
    const ejs = require("ejs");
    const mongoose = require("mongoose");
    const session = require("express-session");
    const passport = require("passport");
    const passportLocalMongoose = require('passport-local-mongoose');
    const GoogleStrategy = require('passport-google-oauth20').Strategy;
    const findOrCreate = require('mongoose-findorcreate');
    
    const app = express();
    
    app.use(express.static("public"));
    app.set("view engine", "ejs");
    app.use(bodyParser.urlencoded({
        extended: true
    }));
    // save user sessionusing cookies
    app.use(session({
        secret: 'keyboard cat',
        resave: false,
        saveUninitialized: true,
    }));
    
    //initializa passport and use it to manage sessions
    app.use(passport.initialize());
    app.use(passport.session());
    
    mongoose.connect('mongodb://localhost:27017/userDB', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false,
        useCreateIndex: true
    });
    mongoose.set("useCreateIndex", true);
    
    const userSchema = new mongoose.Schema({
        email: String,
        password: String
    });
    
    userSchema.plugin(passportLocalMongoose);
    userSchema.plugin(findOrCreate);
    
    const user = mongoose.model("User", userSchema);
    
    // use static authenticate method of model in LocalStrategy
    passport.use(user.createStrategy());
    
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });
    
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });
    
    passport.use(new GoogleStrategy({
            clientID: process.env.GOOGLE_CLIENT_ID,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET,
            callbackURL: "http://localhost:3000/auth/google/secrets",
            userProfileURL: "https: //www.googleapis.com/oauth2/v3/userinfo"
    
        },
        function(accessToken, refreshToken, profile, cb) {
            console.log(profile);
            user.findOrCreate({ googleId: profile.id }, function(err, user) {
                return cb(err, user);
            });
        }
    ));
    
    
    app.get("/", function(req, res) {
        res.render("home");
    });
    app.get('/auth/google',
        passport.authenticate('google', { scope: ['profile'] }));
    
    app.get('/auth/google/secrets',
        passport.authenticate('google', { failureRedirect: '/login' }),
        function(req, res) {
            // Successful authentication, redirect secrets.
            res.redirect('/secrets');
        });
    
    app.get("/login", function(req, res) {
        res.render("login");
    });
    app.get("/register", function(req, res) {
        res.render("register");
    });
    app.get("/secrets", function(req, res) {
        if (req.isAuthenticated) {
            res.render("secrets");
        } else {
            res.redirect("/login");
        }
    });
    app.get("/logout", function(req, res) {
        req.logout();
        res.redirect("/");
    });
    
    
    app.post("/register", function(req, res) {
        user.register({
            username: req.body.username
        }, req.body.password, function(err, user) {
            if (err) {
                console.log(err);
                res.redirect("/register");
            } else {
                passport.authenticate("local")(req, res, function() {
                    res.redirect("/secrets");
                });
            }
        });
    
    });
    
    
    app.post("/login", function(req, res) {
    
        const user = new user({
            name: req.body.username,
            password: req.body.passwword
        });
        req.login(user, function(err) {
            if (err) {
                console.log(err);
            } else {
                passport.authenticate("local")(req, res, function() {
                    res.redirect("/secrets");
                });
            }
        });
    
    });
    
    
    app.listen(3000, function() {
        console.log("Server started on port 3000");
    });ode here
    

    经过几次改变,它对我起了作用

  • 在passport.deserializeUser()方法中,应该使用“user”而不是“user”

  • 在passport.use(新谷歌策略…)中,userProfileURL值有一个输入错误

    userProfileURL:“https://www.googleapis.com/oauth2/v3/userinfo"

  • 请尝试这些更改。希望有帮助。
    注意:saveUninitialized的默认值也是true。在您的场景中,该值应该为false,但true也没有坏处。

    经过几处更改,它对我有效

  • 在passport.deserializeUser()方法中,应该使用“user”而不是“user”

  • 在passport.use(新谷歌策略…)中,userProfileURL值有一个输入错误

    userProfileURL:“https://www.googleapis.com/oauth2/v3/userinfo"

  • 请尝试这些更改。希望有帮助。 注意:saveUninitialized的默认值也是true。在您的场景中,该值应该为false,但true也不会有任何影响