CORS 标头“Access-Control-Allow-Origin”丢失。状态代码:404(fastify-oauth2 + React)

问题描述 投票:0回答:1

跨源请求被阻止:同源策略不允许使用react中的fastify-oauth2读取远程资源a github oauth api

报错如下:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://github.com/login/oauth/authorize?response_type=code&client_id=<client_id>&redirect_uri=http%3A%2F%2Flocalhost%3A4000%2Foauth2%2Fgithub%2Fcallback&scope=user&state=<state>. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.

fastify-oauth2 配置选项:

const oAuthOptions: FastifyOAuth2Options = {
  name: "githubOAuth2",
  scope: ["user"],
  credentials: {
    client: {
      id: "<CLIENT_ID>",
      secret: "<CLIENT_SECRET",
    },
    auth: oAuth2Plugin.GITHUB_CONFIGURATION,
  },
  startRedirectPath: "/oauth2/github/login",
  callbackUri: "http://localhost:4000/oauth2/github/callback",  
};

回调路线:

app.get(
    "/github/callback",
    async (req: FastifyRequest, reply: FastifyReply) => {
      try {
        const { token } =
          await app.githubOAuth2.getAccessTokenFromAuthorizationCodeFlow(req);
       
        console.log({ userAuthToken }, "Authenticated successfully!");
        reply.send({ token });
      } catch (error) {
        reply.code(500).send("Failed to authenticate");
      }
    }
  );

cors 配置选项:尝试了多个选项

const corsOptions: FastifyCorsOptions = {
  origin: "*",
  // ["https://github.com", "http://localhost:5173"],
  credentials: true,
  // allowedHeaders: [
  //   "Access-Control-Allow-Origin",
  //   "Access-Control-Allow-Headers",
  //   "Origin, X-Requested-With, Content-Type, Accept",
  // ],
};

React代码调用api:

const handleOAuth = async () => {
  try {
    const response = await axios.get("http://localhost:4000/oauth2/github/login");
    console.log(response.data);
    history("/user");
  } catch (error) {
    console.error(error);
  }
};

当我从index.html srcipt调用api时

window.location.assign
它的工作方式就好像它替换了url并调用它一样。 但是当使用 axios 从 React 应用程序调用时,它显示 cors 错误

reactjs oauth-2.0 cors fastify github-oauth
1个回答
0
投票

您应该在 axios 请求中包含凭据

您可以如何实现这一点:

const response = await axios.get("http://localhost:4000/oauth2/github/login", {
 withCredentials: true
});

看看有没有帮助!

顺便说一句,有谁知道为什么 @fastify/cors 在我的例子中没有设置会话 cookie:

  • 我正在使用本地和谷歌身份验证与 fastify
  • session-cookie 按本地身份验证的预期工作,但不适用于谷歌身份验证
© www.soinside.com 2019 - 2024. All rights reserved.