Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport google authentication with javascript fullstack

I'm trying to add google authentication with passport in my application, that has been generated using yeoman fullstack-generator.

Inside my login controller i have this request:

$scope.googleAuth = function(){
  $http.get('/auth/google');
};

but when i call this function i have this error:

XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=h…d=<my-client-ID-here>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.

I tried to fix that problem adding a middleware layer in my express.js file:

app.use(function (req, res, next) {

  // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:9000');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  next();
});

but it still not working. Is this the right solution? and is it safe?

like image 915
Biagio Chirico Avatar asked Aug 18 '26 22:08

Biagio Chirico


1 Answers

I fixed the problem using an hyperlink instead of a button as following

<a target="_self" href="/auth/google" class="btn btn-danger">Google+</a>

I used target="_self"otherwise angular redirects to home page because, I think, it considers /auth/google as a route of my app.

like image 193
Biagio Chirico Avatar answered Aug 21 '26 19:08

Biagio Chirico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!