I'm developing simple webapp with node and react using facebook authentication. I've also followed a few tutorials about this topic, but in those implementations client and backend were on the same server. Here I've backend server works on localhost:5000 and react app on localhost:3000. In react package.json there is proxy to backend, so client knows how to call api.
When I click on 'sign in with facebook' button, I'm redirect to facebook page, where I authorize application and receive to my client app profile id and other requested user iformation. Hovewer, when I'm sending user info to my backend server, I can see in console this error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fapi%2Fauth%2Ffacebook%2Fcallback&client_id=1617633901657669. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
And below that you can see:
TypeError: NetworkError when attempting to fetch resource. [Learn More]
Facebook app settings:
OAuth router:
const router = require('express').Router();
const passport = require('../config/facebook-passport');
router.get('/facebook', passport.authenticate('facebook'));
router.get('/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
console.log('Successful authentication, redirect home');
res.redirect('/');
});
module.exports = router;
Passport-facebook:
const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;
passport.use(new FacebookStrategy({
clientID: process.env.CLIENTID,
clientSecret: process.env.CLIENTSECRET,
callbackURL: "/api/auth/facebook/callback"
},
function(accessToken, refreshToken, profile, done) {
console.log(accessToken, refreshToken, profile)
}
));
module.exports = passport;
app.js:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: '3cr3ts#tr',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/api/users', users);
app.use('/api/oauth', oauth);
app.get('/api/hello', ensureAuthenticated, function(req, res, next) {
res.send({express: 'Hello there'})
});
app.listen(5000);
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.status(401);
res.send({express: "you need to authenticate"})
}
Login react component:
import FacebookLogin from 'react-facebook-login';
class Login extends Component {
sendFacebookResponse(response) {
fetch(`/api/oauth/facebook?${Object.keys(response).map(k => k+'='+response[k]).join('&')}`)
}
render() {
return (
<FacebookLogin
appId="1617633901657669"
autoLoad={true}
fields="name,email,picture"
callback={this.sendFacebookResponse} />
);
}
}
Is my app configured correctly? How can I get rid of CORS error? Any help or suggestions will be appreciated.