4

So we have a "web" server and an API server - the web server serves up HTML and the API server serves up JSON.

We use Passport's Twitter strategy to authenticate on the web server.

My question is - what is the best way to check on the API server that the user who has authenticated with the web server is also authenticated with the API?

My assumption is that we should put most of the Passport code into the web server, have the user authenticate with it as usual with Passport, and use some middleware in the API server like so to check if the user is logged in (has a session):

app.use(passport.initialize());
app.use(passport.session());

app.use(expressSession({
   secret: 'keyboard cat',
   store: new MongoStore({mongooseConnection: mongoose.connection})
}));


app.use(function(req,res,next){


    if(req.isAuthenticated()){
        next();
    }
    else{
        console.log('unauthenticated request');
        res.status(403).json({error:'unauthorized request'});
    }

});

however, the above doesn't seem to be enough. I am utterly confused about exactly what code I need on the API server - I believe I need to read from the same session store that the web server writes to and to look at a token in the request to the API server and compare it with a token in the session store?

I am not sure I understand what the req.isAuthenticated() function does? It seems like I now need to write my own req.isAuthenaticated() function which reads from the session store asynchronously...

Does anyone have an example of how to do this right?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

1

You might be able to do as you said - authenticate using the web server and just verify that they are authenticated using the API.

Providing that both servers share the same remote session store, and both endpoints have access to the express session cookie, you should be able to implement something like this for the API:

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated())
    return next();
  else
    // Not authenticated
}

Or

if (req.user) {
    // logged in
  } else {
    // not logged in
}

As middleware (as you showed in your example), or on a per-route basis.

This may not be viable if you can't access the same, shared, session cookie though. Other options may be available depending on what structure your app is built in ie. - if the web server is speaking directly to the API.

You can read the raw req.isAuthenticated function from the passport github.

Community
  • 1
  • 1
Ash
  • 6,483
  • 7
  • 29
  • 37