3

So I'm trying to enable google authentication with passport google oauth20. I have created a button that submits the form to the backend like this.

<form className="auth-form" action ="/api/v1.0/authentication/google" method="get">
  <button type="submit" className="btn btn-light" >
    <img width="20px" style={{ marginBottom: "3px", marginRight: "1em" }} alt="Google sign-in" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G%22_Logo.svg/512px-Google_%22G%22_Logo.svg.png" />
    Sign up with Google
  </button>
</form>

But this does not allow me to capture the response of the get request. Therefore I tried making an onClick function that calls a function that makes an axios.get() request to the same URL like this

<div className="auth-form">
  <button className="btn btn-light" onClick={this.googleAuthenticate}>
    <img width="20px" style={{ marginBottom: "3px", marginRight: "1em" }} alt="Google sign-in" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G%22_Logo.svg/512px-Google_%22G%22_Logo.svg.png" />
    Sign up with Google
  </button>
</div>

This is inside my class component

class Register extends Component {
  constructor(props) {
    super(props);
    this.googleAuthenticate = this.googleAuthenticate.bind(this);
  }

  googleAuthenticate(){
    axios.get("/api/v1.0/authentication/google")
    .then(({data})=>{
      console.log("this is data",data);
    });
  }
}

But this does not redirect me to the google signing page. Please give me some advice on what to do. The error I get when I click the button is

Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth? response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fv1.0%2Fgoogle%2Fcallback&scope=profile%20email&client_id=976971922840-p9eobg6v863nppicf7vsatfup1q82qjt.apps.googleusercontent.com' (redirected from 'http://localhost:3000/api/v1.0/authentication/google') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The server side code is

router.get("/api/v1.0/authentication/google", restrict({ unregistered: 
true, registered: false }), passport.authenticate("google", { scope: 
["profile", "email"] }));

router.get("/api/v1.0/google/callback", restrict({ unregistered: true, registered: false }), passport.authenticate("google", { failureRedirect: "/register" }), (req, res,next) => {
    res.redirect("/");
});
Mathew Pius
  • 65
  • 1
  • 7

1 Answers1

0

I found a solution:

[Passportjs][Angular5] No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access

<a href="http://localhost:3000/login/google">Google</a>

Where "localhost:3000/login/google" goes to app.get('/login/google', passport.authenticate('google', { scope: ['profile','email']}) );

plutownium
  • 1,220
  • 2
  • 9
  • 23