Reputation: 376
I've set up an angular/nodejs(express) application with google authentication but whenever I request to google oauth through angular app it throws a cors error but if I request directly from browser it works as it should.
Backend is running on port 3000 and angular is running on 4200.
I'm using cors
package to allow all cors requests in server.js:
app.use(passport.initialize());
// Passport Config
require('./config/passport')(passport);
// Allowing all cors requests
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/users', usersRouter);
app.use('/auth', authRouter);
Passport config:
passport.use(
new GoogleStrategy(
keys,
(token, refreshToken, profile, done) => {
process.nextTick(() => {
User.findOne({ email: email })
.then(user => {
if (user) {
return done(null, user);
}
})
.catch(err => console.log(err));
});
}
)
);
This is the google authentication route:
router.get('/google', passport.authenticate('google', {
scope: ['profile', 'email'],
session: false
}),
(req, res) => {
// Create JWT payload
const payload = {
id: req.user.id,
email: req.user.email
};
jwt.sign(payload, secret, expires, (err, token) => {
res.json(token);
});
}
);
And here is angular request:
googleAuth() {
return this.http.get<any>('http://localhost:3000/auth/google').pipe(
map(user => {
if (user) {
localStorage.setItem(
'currentUser',
JSON.stringify(user)
);
}
return user;
})
);
}
Error in chrome console:
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 'null' is therefore not allowed access
I've also authorized JavaScript origins in google developers console: origins
I'm pretty new to angular and nodejs and I have read all the similar questions but couldn't find a workaround to this problem.
Upvotes: 1
Views: 1547
Reputation: 243
Try out this method of directly calling the URL: ( Pardon if I missed something syntactically, but basically this is the idea )
googleAuth(){
window.open('/google',"mywindow","location=1,status=1,scrollbars=1, width=800,height=800");
let listener = window.addEventListener('message', (message) => {
//message will contain google user and details
});
}
and in server you have passport strategy set I assume, Now
router.get('/google', passport.authenticate('google', {
scope: ['profile', 'email'],
session: false } ))
router.get('/google/callback',
passport.authenticate('google', { failureRedirect: '/auth/fail' }),
function(req, res) {
var responseHTML = '<html><head><title>Main</title></head><body></body><script>res = %value%; window.opener.postMessage(res, "*");window.close();</script></html>'
responseHTML = responseHTML.replace('%value%', JSON.stringify({
user: req.user
}));
res.status(200).send(responseHTML);
});
Upvotes: 1