What I'm trying to accomplish is to do user authentication via ajax using passport. The recommended way of using passport is to trigger the authorisation process via a GET request which gets triggered using a regular <a> tag. After successful (or failed) authentication there is a redirect to a new page. Now instead of using a html link to trigger the route I want to do it via ajax. The problem here is that when I try this with a third party authentication strategy such as passport-facebook I get a CORS error:
XMLHttpRequest cannot load [the facebook auth URL]' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8080' is therefore not allowed access.
Here is the relevant server side code:
// route for facebook authentication and login
app.get('/auth/facebook', passport.authenticate('facebook', { scope : ['email'] }));
// handle the callback after facebook has authenticated the user
app.get('/auth/facebook/callback', (req, res, next) => {
passport.authenticate('facebook', (err, user, info) => {
req.login(user, function(err) {
if(err) return next(err);
return res.status(200).json({
success: "All good man!"
});
})
})(req, res, next);
});
While in the browser I simply do:
axios.get('/auth/facebook').then((response) => {
console.log(response);
});
I found several similar questions but none of them seemed to have a satisfying answer. Is there a way to actually do this? Or a smart workaround? Maybe a way to still send back a JSON response even if the route was triggered using an html link?
via Flavio
No comments:
Post a Comment