在反应和 deno 中使用 google oauth 阻止跨域请求

Cross-Origin Request Blocked with google oauth in react and deno

我有一个使用 oak 的 deno 服务器:

import { CORS } from "https://deno.land/x/oak_cors@v0.1.1/mod.ts";
export { Application } from "https://deno.land/x/oak@v10.5.1/mod.ts";


const app = new Application();

app.use(CORS({
    origin: '*', credentials: true
}))

app.use('/auth/google/url', (ctx) => {
 const oauth2Client = new OAuth2Client({
      clientId: env.get("CLIENTID") as string,
      clientSecret: env.get("CLIENTSECRET") as string,
      redirectUri: env.get("REDIRECTURI") as string,
      authorizationEndpointUri: env.get("AUTHORIZATIONENDPOINTURI") as string,
      tokenUri: env.get("TOKENURI") as string,
      defaults: {
        scope: "profile email openid",
      },
    });
  ctx.response.redirect(
      return oauth2Client.code.getAuthorizationUri();
    );
});

我从 React 应用调用 api:

import React from 'react'

export default function App(){
  const handleClick = () => {
     fetch('/auth/google/url', {method: 'get', redirect: 'follow'})
    .then((response) => {
      if (response.status === 302) {
        window.location.href = response.url
      }
    })

  }

  return(
    <Button onClick={handleClick}>SignIn with Google</Button>
  )

}

我在package.json中设置了代理:

"proxy": "http://127.0.0.1:5000"

我在浏览器控制台中收到此错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=XXXXXXXXXXX&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fauth%2Fgoogle%2Fcallback&scope=profile+email+openid. (Reason: CORS request did not succeed). Status code: (null).

我通过更新 api 解决了这个问题,所以我没有将用户重定向到回调页面,而是 return url 和状态代码:

app.use('/auth/google/url', (ctx) => {
 const oauth2Client = new OAuth2Client({
      clientId: env.get("CLIENTID") as string,
      clientSecret: env.get("CLIENTSECRET") as string,
      redirectUri: env.get("REDIRECTURI") as string,
      authorizationEndpointUri: env.get("AUTHORIZATIONENDPOINTURI") as string,
      tokenUri: env.get("TOKENURI") as string,
      defaults: {
        scope: "profile email openid",
      },
    });

      ctx.response.body = oauth2Client.code.getAuthorizationUri();
      ctx.response.status = 302
});

所以按钮处理程序更新如下:

const handleClick = async () => {
   const response =  await fetch('http://localhost:3000/auth/google/url')
   const data = await response.json()
   if (data) {
     window.location.href = data
   }
  }