What is the best practice to use Oauth2, React, Node.js and Passport.js to authenticate user with Google sign on button?

后端 未结 3 1498
长发绾君心
长发绾君心 2020-12-30 10:41

I want to have a login button in my website so when a user clicks on it, the user can use their Google credentials. I\'d like to ideally perform the authentication server si

3条回答
  •  长情又很酷
    2020-12-30 11:19

    I faced the same issue. This article is Gold link

    1.In auth route File I had following code

     const CLIENT_HOME_PAGE_URL = "http://localhost:3000";
    
      // GET  /auth/google
      // called to authenticate using Google-oauth2.0
      router.get('/google', passport.authenticate('google',{scope : ['email','profile']}));
    
    
      // GET  /auth/google/callback
      // Callback route (same as from google console)
       router.get(
        '/google/callback',  
        passport.authenticate("google", {
        successRedirect: CLIENT_HOME_PAGE_URL,
        failureRedirect: "/auth/login/failed"
       })); 
    
       // GET  /auth/google/callback
      // Rest Point for React to call for user object From google APi
       router.get('/login/success', (req,res)=>{
         if (req.user) {
             res.json({
              message : "User Authenticated",
             user : req.user
            })
         }
         else res.status(400).json({
           message : "User Not Authenticated",
          user : null
        })
      });
    

    2.On React Side After when user click on button which call the above /auth/google api

      loginWithGoogle = (ev) => {
        ev.preventDefault();
        window.open("http://localhost:5000/auth/google", "_self");
      }
    

    3.This will redirect to Google authentication screen and redirect to /auth/google/callback which again redirect to react app home page CLIENT_HOME_PAGE_URL

    4.On home page call rest end point for user object

    (async () => {
      const request = await fetch("http://localhost:5000/auth/login/success", {
       method: "GET",
       credentials: "include",
       headers: {
        Accept: "application/json",
         "Content-Type": "application/json",
        "Access-Control-Allow-Credentials": true,
      },
    });
    
    const res = await request.json();
       //In my case I stored user object in redux store
       if(request.status == 200){
         //Set User in Store
        store.dispatch({
          type: LOGIN_USER,
          payload : {
            user : res.user
         }
        });
      }
    
    })();
    

    5.last thing add cors package and following code in server.js/index.js in node module

    // Cors
    app.use(
      cors({
        origin: "http://localhost:3000", // allow to server to accept request from different origin
        methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
        credentials: true // allow session cookie from browser to pass through
       })
    );
    

提交回复
热议问题