使用Google OAuth的CORS [英] CORS with google oauth

查看:53
本文介绍了使用Google OAuth的CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的应用中实现google登录,但遇到了一个令人沮丧的问题。
我的react应用程序运行在端口3000上,我的特快服务器运行在端口5000上。我还使用护照对用户进行身份验证。
当我尝试通过Google登录时,遇到波纹管时遇到错误

I'm trying to implement google login in my app and I ran into a frustrating problem. I have my react app running on port 3000 and my express server is on port 5000. I'm also using passport to authenticate users. When I'm trying to login via google and I hit the route bellow I'm get the error

否'Access- Control-Allow-Origin'标头出现在请求的资源上。因此,不允许访问源'http:// localhost:3000'。

根据我的阅读,我必须在以下位置设置CORS快递服务器(我使用cors库完成)。即使这样做,我仍然会收到此错误。
以下是代码:

From what I read, I have to set up CORS on the express server (which I did using the cors library). Even doing so, I still get this error. Bellow is the code:

护照:

module.exports = passport => {
  passport.use(
    new GoogleStrategy(
      {
        clientID: keys.googleClient,
        clientSecret: keys.googleSecret,
        callbackURL: "/auth/google/callback"
      },
      (token, refreshToken, profile, done) => {
        return done(null, {
          profile: profile,
          token: token
        });
      }
    )
  );

路线:

router.post(
  "/auth/google",
  passport.authenticate("google", {
    session: false,
    scope: ["profile"]
  }),
  (req, res) => {
    if (!req.token) {
      return res
        .status(401)
        .json("Not authorized");
    } else {
      console.log(req.token);
    }
  }
);

要启用CORS,我所做的只是包括cors库并与express一起使用:

To enable CORS all I did was include the cors library and use it with express:

//enables cors
app.use(cors()); 

也许我误会了整个CORS。我应该如何处理?

Maybe I misunderstood this entire CORS thing. How should I approach this?

推荐答案

您正在从localhost:3000向localhost:5000发出请求,它们的来源不同,因此出于安全考虑,浏览器将不会发出此请求。

you are making request from localhost:3000 to localhost:5000 they do not have same origin, so for security browser will not make this request. to circumvent you have to use proxy.

因为您没有提到webpack,所以我相信您使用的是CRA(create-react-app)。

since you did not mention about webpack I belive you are using CRA (create-react-app). this is how you should set up proxy in CRA.

在客户端目录中:

npm i http-proxy-middleware --save

创建setupProxy.js文件在client / src中。无需将其导入任何地方。 create-react-app将查找该目录

Create setupProxy.js file in client/src. No need to import this anywhere. create-react-app will look for this directory

将代理添加到该文件中。

Add your proxies to this file.

const proxy=require("http-proxy-middleware")
module.exports=function(app){
    app.use(proxy(['/auth/google'],{target:"http://localhost:8888"}))}

做一个代理,如果有人尝试访问我们的react服务器上的路由/ auth / google,则自动将请求转发到localhost:5000。

We are saying that make a proxy and if anyone tries to visit the route /auth/google on our react server, automatically forward the request on to localhost:5000.

这篇关于使用Google OAuth的CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆