0

I'm currently working on building a REST API where users can authenticate themselves via different passport strategies (google, facebook). The authentication has to be done without a session.

Now I've already worked on the local strategy and that works like so; application POST /login to API and then when the user entered the right credentials they will get some payload back like so

[
    {
        "tokenType": "refresh",
        "expiresIn": 604800000,
        "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTUsImlhdCI6MTY0MDc4NzA4MCwiZXhwIjoxNjQxMzkxODgwfQ.zdxdpX8NkiSTsbZj0xOd18RdbLjeSsQpkikLGW71xrE"
    },
    {
        "tokenType": "access",
        "expiresIn": 7200000,
        "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTUsImlhdCI6MTY0MDc4NzA4MCwiZXhwIjoxNjQwNzk0MjgwfQ.EBDuJqQYT-D0bnYbC76_khe6b29c80R4pMyEaBNKLKE"
    }
]

However, the problem with the google and facebook strategy is that they work via OAuth. I'm struggling to find a way to send the above information (like with my local strategy) to the client after the OAuth authentication has succeeded.

These OAuth services work with a return URL like /auth/facebook/return. But this return URL is on the API which then can't send the information over to the client (or can it?).

How can I do this?

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
Martijn Ebbens
  • 514
  • 2
  • 5
  • 14

1 Answers1

0

You can use passport-facebook-token that is altogether a different strategy from passport-facebook. It does provide the token that can be used to authenticate users.

passport.use('facebook-token', new FacebookTokenStrategy({
    clientID        : "your-client-id",
    clientSecret    : "secret"
  },
  function(accessToken, refreshToken, profile, done) {
    // console.log(profile);

     var user = {
        'email': profile.emails[0].value,
        'name' : profile.name.givenName + ' ' + profile.name.familyName,
        'id'   : profile.id,
        'token': accessToken
    }

    // You can perform any necessary actions with your user at this point,
    // e.g. internal verification against a users table,
    // creating new user entries, etc.

    return done(null, user); // the user object we just made gets passed to the route's controller as `req.user`
  }
));

Use passport.authenticate(), specifying the 'facebook-token' strategy, to authenticate requests. You need to use it as middleware for any route to authenticate.

app.post('/auth/facebook/token',
  passport.authenticate('facebook-token'),
  function (req, res) {
    // do something with req.user
    res.send(req.user? 200 : 401);
  }
);

I would suggest you check this link and the code under the hood that is well documented.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35