CORS with google oauth

泄露秘密 提交于 2020-01-25 07:17:08

问题


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

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

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:

PASSPORT:

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
        });
      }
    )
  );

ROUTE:

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);
    }
  }
);

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

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

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


回答1:


The browser error message provides a hint as to the correct origin to set:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

Per the docs:

app.use(cors({ origin: "http://localhost:3000" }))




回答2:


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.

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.

In the client side directory:

npm i http-proxy-middleware --save

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"}))}

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.



来源:https://stackoverflow.com/questions/52181178/cors-with-google-oauth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!