1
votes

NodeJs configured and running fine with passportJS OAuth2, but the requirement is angular should call node api, both are runs in different ports, calling all nodeJS's rest API from angular and it runs fine using proxy.conf.json, while calling /googleauth/redirect from angular getting error response.

Response :

Failed to load https://accounts.google.com/o/oauth2/v2/auth?response_type=code... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Google API Setting :

Restrictions

Authorised JavaScript origins :

http://localhost:4200
http://localhost:8088

Authorised redirect URIs :

http://localhost:4200/api/googleauth/redirect
http://localhost:8088/api/googleauth/redirect

Update 1 : CORS to app.js (new): but no changes.

var cors = require('cors');
var app = express();
app.use(cors());
app.options('*', cors());
app.use('/api',cors(),require('./routes/api'));

Update 2 : api.js

router.get('/google', passport.authenticate('google', { scope: ['profile','email'] }));

passport setup

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20');
const userModel = require('../model/user');

passport.serializeUser((user,done)=>{
  done(null,user.id);
});

passport.deserializeUser((id,done)=>{
  userModel.findById(id).then((user)=>{
    done(null,user);
  })
});

passport.use(
  new GoogleStrategy({
    callbackURL:'/api/googleauth/redirect',
    clientID:'',
    clientSecret:''
  },(accessToken,refreshToken,profile,done) =>{
    console.log("call back function fired");
    //console.log(accessToken);
    userModel.findOne({email:profile.emails[0].value,authType:'google'},function(err,user){
        if(user){
          done(null,user);
        }else{
          done(null,user);
        }
    });
  }))
1
Can you share the CORS configuration you are using in your nodejs REST API? - Qiong Wu
@QiongWu - added my cors config (updated my question) - 151291
@QiongWu - other api's are working fine, only passportjs oauth2 not runs. - 151291
ok, so from what I can see the issue is not with your nodejs cors, I think you are implementing the oauth redirect flow in the incorrect way. Is it possible that you are trying to directly open /google with $http.get? in this case angular will try to follow the redirect instead of changing the location of the browser to the google URL, causing the CORS error on the google URL. instead you need to make sure that the redirect causes a redirect on the browser - Qiong Wu

1 Answers

0
votes

I resolved this problem with a tutorial https://medium.com/@ahsan.ayaz/how-to-handle-cors-in-an-angular2-and-node-express-applications-eb3de412abef

Only lack a detail... next to the lines import { BrowserXhr } from ‘@angular/http’; and import {CustExtBrowserXhr} from ‘./app/path-to-file/cust-ext-browser-xhr’; you should add import { LocationStrategy, HashLocationStrategy } from '@angular/common';