Search code examples
passport.jsloopbackjsloopbackpassport-facebook

How to get accessToken generated whit passport in loopback


I am integrating passport with loopback, and works fine, the problems is how to get the access token.

I have a web app (served in a different server than loopback) so:

  1. Make the request (in the loopback backend)
  2. This redirect me to Facebook, approve it
  3. Return to loopback (do the passport work)
  4. Now, how can i get the accessToken generated in my web app?

I can redirect (if login is successful) to my web app, but i lose the accessToken in the progress.

Any ideas?

i make the request

SOLUTION:

The access token is seted by loopback in the cookies, so when redirect back to the web app, can access by:

 document.cookie

if you wanna pass through a variable:

var access_token = document.cookie.replace(/(?:(?:^|.*;\s*)access_token\s*\=\s*([^;]*).*$)|^.*$/, "$1")
var userId = document.cookie.replace(/(?:(?:^|.*;\s*)userId\s*\=\s*([^;]*).*$)|^.*$/, "$1")

BUT

if you use different URLs for the backend and the frontend, you cant so i recommend use the solution of this post


Solution

  • I hope, I got the idea. Here is the flow I follow with passport/facebook strategy.
    1) Client side(web app): window.location = http://urlServerName:port/passport/facebook This can be a redirect on server side also.
    2) User enter credentials on facebook.
    3) Facebook redirect to callback.

    router.get('/passport/facebook', passport.authenticate('facebook'));
    router.get('/passport/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }),
       (req, res) => {
    
          let url = req.url; // url contains the code
          let urs = req.usr; // user info.
          // You can set a cookie with the info you want. This can be the auth code, the user profile or a JWT generated in the same request.
          res.cookie("data",usr,{httpOnly:true});            
          res.redirect('urlWebApplication');          
    });
    

    4) Inside your callback you can set a cookie with the information you want. This way it can be access in your webapp.
    Hope this help to clarify.