使用Passport.js和Ngrok时,Req.user由于CORS而不确定

发布于 2025-01-31 05:18:02 字数 2677 浏览 3 评论 0原文

前端是http localhost,后端是https ngrok。当我在前端与oauth登录并尝试在后端致电req.user时,它说未定义。

另外,如果后端和前端都使用nGrok,则会发生同样的问题。但是,如果我在后端不使用NGrok并使用http的Localhost,则一切正常。

ngrok命令:ngrok-主持人http 8000

express:app.ts

import "~/database";
import "~/libs/passport";

import express from "express";
import session from "express-session";
import cors from "cors";
import passport from "passport";
import { router } from "~/routes";

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({ secret: "asdf", resave: false, saveUninitialized: false }));

app.use(cors({ origin: true, credentials: true }));
app.use(passport.initialize());
app.use(passport.session());

app.use("/", router);
app.listen(8000, () => {
  console.log("Server has been started...");
});

react:app.tsx

import React, { useCallback, useEffect } from "react";
import logo from "./logo.svg";
import "./App.css";

function App() {
  const handleSignIn = useCallback(() => {
    window.location.assign("http://localhost:8000/api/auth");
  }, []);

  useEffect(() => {
    const process = async () => {
      const result = await fetch("http://localhost:8000/api/profile", {
        credentials: "include",
      });
      console.log(await result.json());
    };

    process();
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <button onClick={handleSignIn}>DASD</button>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

没有错误,但是req.user不确定。

/api/auth

api.get("/", passport.authenticate("github", { scope: ["repo"] }));

/api/auth/pallback

api.get(
  "/",
  passport.authenticate("github", {
    failureRedirect: failureURL,
    successRedirect: frontendOrigin,
  })
);

/profile,状态为401。/api/profile

add:并在前端呼叫/ api

api.get("/", async (req, res) => {
  if (!req.isAuthenticated()) {
    return res.status(401).json();
  }

  const profile: Profile = {
    username: req.user.username,
    name: req.user.name,
    avatarURL: req.user.avatarURL,
  };
  return res.status(200).json(profile);
});

The frontend is http localhost and the backend is https ngrok. When I log in with OAuth in the frontend and try to call req.user in the backend, it says undefined.

Also, if both the backend and the frontend use ngrok, the same problem occurs. However, if I do not use ngrok in the backend and use the localhost which is http, everything works fine.

ngrok command: ngrok --host-header http 8000

Express: app.ts

import "~/database";
import "~/libs/passport";

import express from "express";
import session from "express-session";
import cors from "cors";
import passport from "passport";
import { router } from "~/routes";

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({ secret: "asdf", resave: false, saveUninitialized: false }));

app.use(cors({ origin: true, credentials: true }));
app.use(passport.initialize());
app.use(passport.session());

app.use("/", router);
app.listen(8000, () => {
  console.log("Server has been started...");
});

React: App.tsx

import React, { useCallback, useEffect } from "react";
import logo from "./logo.svg";
import "./App.css";

function App() {
  const handleSignIn = useCallback(() => {
    window.location.assign("http://localhost:8000/api/auth");
  }, []);

  useEffect(() => {
    const process = async () => {
      const result = await fetch("http://localhost:8000/api/profile", {
        credentials: "include",
      });
      console.log(await result.json());
    };

    process();
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <button onClick={handleSignIn}>DASD</button>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

There's no error, but req.user is undefined.

/api/auth

api.get("/", passport.authenticate("github", { scope: ["repo"] }));

/api/auth/callback

api.get(
  "/",
  passport.authenticate("github", {
    failureRedirect: failureURL,
    successRedirect: frontendOrigin,
  })
);

Add: and call /api/profile in frontend, status is 401.

/api/profile

api.get("/", async (req, res) => {
  if (!req.isAuthenticated()) {
    return res.status(401).json();
  }

  const profile: Profile = {
    username: req.user.username,
    name: req.user.name,
    avatarURL: req.user.avatarURL,
  };
  return res.status(200).json(profile);
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

假面具 2025-02-07 05:18:02

显然,您不能

https://ngrok.com/docs/docs/faq

与HTTP基本身份验证的CORS

NGrok的HTTP隧道将与CORS一起使用,但您无法使用Ngrok的
- 基本实体选项。 NGrok的HTTP隧道允许您指定基本身份验证凭证以保护您的隧道。但是,Ngrok
在所有请求中执行此政策,包括前飞行选项
CORS规格要求的请求。在这种情况下,您的
应用程序必须实施自己的基本身份验证。

这可能是因为您yuse 凭据:true,ngrok已经使用- BASIC-AUTH选项。

您可以分享错误的错误吗?

Apparently you can't

https://ngrok.com/docs/faq

CORS with HTTP Basic Authentication

ngrok's HTTP tunnels will work with CORS, but you cannot use ngrok's
--basic-auth option. ngrok's HTTP tunnels allow you to specify basic authentication credentials to protect your tunnels. However, ngrok
enforces this policy on all requests, including the preflight OPTIONS
requests that are required by the CORS spec. In this case, your
application must implement its own basic authentication.

It might be because you yuse credentials: true, ngrok already uses --basic-auth option.

Can you share the error thrown ?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文