Search code examples
node.jspassport.jspassport-google-oauth2

Easy Node Authentication: Google


I am trying to login with google to my application, but it shows an error like shown below,

XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_ur…d=410427634474-u3tpasmj4r80s6v20o54s85fikhotl79.apps.googleusercontent.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I have tried something like below

app.js

passport.use(new GoogleStrategy({
    clientID        : config.googleAuth.clientID,
    clientSecret    : config.googleAuth.clientSecret,
    callbackURL     : config.googleAuth.callbackURL
},
function(accessToken, refreshToken, profile, done) {
   User.findOrCreate({ googleId: profile.id }, function (err, user) {
     return done(err, user);
   });
}
));


router.get('/pages/auth/loginWithGoogle',
    passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] }));

router.get('/auth/google/callback',
passport.authenticate('google', {
   successRedirect : '/invite-friends',
   failureRedirect : '/pages/auth/login'
}));

Solution

  • $http() it will send an ajax request, that wont work

    The code below opens url in a new window, then if user authorized and everything is ok it will redirect main page to /invite-friends

        vm.loginWithGoogle = function(){
            var win = window.open('/api/pages/auth/loginWithGoogle', "windowname1", 'width=800, height=600'); 
            var REDIRECT = 'callback';
    
            var pollTimer   =   window.setInterval(function() { 
                try {
                    if (win.document.URL.indexOf(REDIRECT) != -1) {
                        window.clearInterval(pollTimer);
                        window.location = window.location.origin + '/invite-friends';
                        win.close();
                    }
                } catch(e) {
                }
            }, 100);
        }
    

    or use it to open url in a current page:

    vm.loginWithGoogle = function(){
        location.href = '/api/pages/auth/loginWithGoogle';
    }