5

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:

  1. enter image description here
  2. enter image description here
  3. enter image description here

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.

3
  • 1
    Take a look at stackoverflow.com/questions/49058042/…
    – Yossi
    Mar 12, 2018 at 20:23
  • Recommended addon does not works and besides, I'm looking for solution, not a hack ;)
    – sawim
    Mar 12, 2018 at 21:14
  • Fully understood. That's why it is a comment and not an answer.
    – Yossi
    Mar 13, 2018 at 15:04

1 Answer 1

1

First of all, I switched from passport-facebook to passport-facebook-token.

Then I added 2 passport strategies. Facebook is used as authentication provider and jwt for authorizing requests.

const FacebookStrategy = require('passport-facebook-token');
const passportJWT = require('passport-jwt');


passport.use(new FacebookStrategy({
    clientID: <FB CLIENT ID>,
    clientSecret: <FB CLIENT SECRET>
},
(token, refreshToken, profile, done) => {
    // here there should be code responsible for fetching user from database based on facebook profile, saving user if it doesn't exist yet etc.

    done(null, user);
}
));


// this will parse jwtPayload (sent as header; "Authorization: Bearer <JWT TOKEN>") into user object, which will be added to request objects in express router endpoints handlers 
passport.use('jwt', new passportJWT.Strategy({
            jwtFromRequest: passportJWT.ExtractJWT.fromAuthHeaderAsBearerToken(),
            secretOrKey: "secret salt"
        }, (jwtPayload, done) => {
            done(null, jwtPayload);
        }));

Then I added endpoint for user authentication. Passport-facebook-token library expects to get facebook access token sended from client application as query param access_token=FACEBOOK_ACCESS_TOKEN. After successful authorization with fb, jwt token can be generated, send to client application and used for request authorization.

const { sign } = require('jsonwebtoken');

router.get(
    '/facebook-token', 
    passport.authenticate('facebook-token', {session: false}), 
    (req, res, next) => {
        res
            .send({
                token: sign(req.user,  "secret salt" /* the same value that was used to configure jwt passport above */, {})                
            })   
    });

And now user should be authenticated, so in other words, should have a jwt token generated in above endpoint. Client application in next requests should add authorization header, which was mentioned before.

Endpoints can be secured by middleware functions provided by passport library, in this case passport.authenticate('jwt', {session: false}) returns a function which uses jwt strategy.

router.get('/secured-endpoint', passport.authenticate('jwt', {session: false}), (req, res, next) => {
    res.send("hello world")

    // there is req.user object that can be used for user specific actions
});

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.