google 登录 oauth 2.0 护照不工作

google login auth2.0 passport is not working

大家好,我正在尝试使用护照中的 google auth2.0 策略登录,一切顺利,但是当我点击我的 google 个人资料时,我收到一条错误消息说

the connection for this site is not secure and local host is given invalid response

您可以在错误页面的图片下方查看

error image

我的APP.JS代码

require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const _ = require("lodash");
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(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "ejs");
app.use(express.static("public"));

app.use(
  session({
    secret: "this is my secret",
    resave: false,
    saveUninitialized: true,
  })
);

app.use(passport.initialize());
app.use(passport.session());

mongoose.connect("mongodb://localhost:27017/userDatabase");

const userSchema = new mongoose.Schema({
  email: String,
  password: String,
  googleId: String
});

userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);

const User = new mongoose.model("User", userSchema);

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.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
      callbackURL: "https://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("/", (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) {
    res.redirect("/secrets");
  }
);

app.get("/register", (req, res) => {
  res.render("register");
});

app.get("/secrets", (req, res) => {
  if (req.isAuthenticated()) {
    res.render("secrets");
  } else {
    res.redirect("/login");
  }
});

app.post("/register", (req, res) => {
  User.register(
    { username: req.body.username },
    req.body.password,
    (err, user) => {
      if (err) {
        console.log(err);
        res.redirect("/register");
      } else {
        passport.authenticate("local")(req, res, () => {
          res.redirect("/secrets");
        });
      }
    }
  );
});

app.get("/login", (req, res) => {
  res.render("login");
});

app.post("/login", (req, res) => {
  const user = new User({
    username: req.body.username,
    password: req.body.password,
  });

  req.login(user, (err) => {
    if (err) {
      console.log(err);
    } else {
      passport.authenticate("local")(req, res, () => {
        res.redirect("/secrets");
      });
    }
  });
});

app.listen(3000, (req, res) => {
  console.log("server is running fine");
});

我正在使用的 NPM 模块

{
  "name": "mongoosetuts",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "dependencies": {
    "body-parser": "^1.19.1",
    "dotenv": "^10.0.0",
    "ejs": "^3.1.6",
    "express": "^4.17.2",
    "express-session": "^1.17.2",
    "lodash": "^4.17.21",
    "mongodb": "^4.1.3",
    "mongoose": "^6.0.12",
    "mongoose-encryption": "^2.1.2",
    "mongoose-findorcreate": "^3.0.0",
    "passport": "^0.5.2",
    "passport-google-oauth20": "^2.0.0",
    "passport-local": "^1.0.0",
    "passport-local-mongoose": "^6.1.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

我的注册页面代码

<%- include('partials/header') %>
<div class="container mt-5">
  <h1>Register</h1>

  <div class="row">
    <div class="col-sm-8">
      <div class="card">
        <div class="card-body">

          <!-- Makes POST request to /register route -->
          <form action="/register" method="POST">
            <div class="form-group">
              <label for="email">Email</label>
              <input type="email" class="form-control" name="username">
            </div>
            <div class="form-group">
              <label for="password">Password</label>
              <input type="password" class="form-control" name="password">
            </div>
            <button type="submit" class="btn btn-dark">Register</button>
          </form>

        </div>
      </div>
    </div>

     <div class="col-sm-4">
      <div class="card social-block">
        <div class="card-body">
          <a class="btn btn-block" href="/auth/google" role="button">
            <i class="fab fa-google"></i>
            Sign Up with Google
          </a>
        </div>
      </div>
    </div> 

  </div>
</div>

<%- include('partials/header') %>

我的登录页面代码

<%- include('partials/header') %>

<div class="container mt-5">
  <h1>Login</h1>

  <div class="row">
    <div class="col-sm-8">
      <div class="card">
        <div class="card-body">

          <!-- Makes POST request to /login route -->
          <form action="/login" method="POST">
            <div class="form-group">
              <label for="email">Email</label>
              <input type="email" class="form-control" name="username">
            </div>
            <div class="form-group">
              <label for="password">Password</label>
              <input type="password" class="form-control" name="password">
            </div>
            <button type="submit" class="btn btn-dark">Login</button>
          </form>

        </div>
      </div>
    </div>

     <div class="col-sm-4">
      <div class="card">
        <div class="card-body">
          <a class="btn btn-block" href="/auth/google" role="button">
            <i class="fab fa-google"></i>
            Sign In with Google
          </a>
        </div>
      </div>
    </div> 

  </div>
</div>

<%- include('partials/footer') %>

我的秘密页面代码

<%- include('partials/header') %>

<div class="jumbotron text-center">
  <div class="container">
    <i class="fas fa-key fa-6x"></i>
    <h1 class="display-3">You've Discovered My Secret!</h1>
    <p class="secret-text">Jack Bauer is my hero.</p>
    <hr>
    
    <a class="btn btn-light btn-lg" href="/logout" role="button">Log Out</a>
    <a class="btn btn-dark btn-lg" href="/submit" role="button">Submit a Secret</a>
  </div>
</div>

<%- include('partials/footer') %>

我的主页代码

<%- include('partials/header') %>


<div class="jumbotron centered">
  <div class="container">
    <i class="fas fa-key fa-6x"></i>
    <h1 class="display-3">Secrets</h1>
    <p class="lead">Don't keep your secrets, share them anonymously!</p>
    <hr>
    <a class="btn btn-light btn-lg" href="/register" role="button">Register</a>
    <a class="btn btn-dark btn-lg" href="/login" role="button">Login</a>

  </div>
</div>

<%- include('partials/footer') %>

我的 EJS HEADER 代码

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Secrets</title>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
  <link rel="stylesheet" href="css/styles.css">
</head>

<body>

我的页脚 EJS 代码

</body>
</html>

guys please help i already check all error your help will be appriciated.

你找到解决办法了吗?如果没有,我会尝试 http://localhost... 而不是 https://localhost... 因为您需要一个有效的自签名证书才能将 https 与 localhost 一起用于通信,例如google。确保您的 google API 设置中也有 http。