tngan / samlify

Node.js library for SAML SSO
https://samlify.js.org
MIT License
601 stars 214 forks source link

How to check whether user is already logged in? #487

Closed deepfriedbrain closed 1 year ago

deepfriedbrain commented 1 year ago

Hi,

Thanks for this wonderful library and the excellent documentation to go along with it.

I'm new to SAML and discovered this library today. I went through all the documentation first, and then within minutes I was able to get my SAML Request and Response working. To implement the login flow, I invoke /spinitsso-redirect route. However, I'm struggling to figure out the login flow that I should implement for my application.

I have a single page app based on AngularJS with a NodeJS backend. The index.js on the server side uses the static middleware to serve the dist folder which has the index.html and other assets.

app.use(express.static(__dirname + '/dist'));

When a user goes to the home page say at www.example.com, the HTML loads the JS, which loads the Angular-based app. But before the Angular app loads up, I want to check whether the user is already logged in. If the user is not logged in, I want to initiate the login flow by making an HTTP Get request to /spinitsso-redirect. After successful login, the user is redirected to /acs route, which redirects the user back to the home page.

app.get('/spinitsso-redirect', (req, res) => {
  const { id, context } = sp.createLoginRequest(idp, 'redirect');
  return res.redirect(context);
});

app.post('/acs', function (req, res) {
  sp.parseLoginResponse(idp, 'post', req)
  .then(parseResult => {
    // use parseResult
    res.redirect('/');
  })
  .catch(console.error);
})

But unless there's a way to conditionally invoke /spinitsso-redirect route from the Javascript based on whether user is logged in, it will go into an infinite loop as the Javascript on the client side would keep invoking this route even after the user has successfully logged in.

So how do I conditionally invoke /spinitsso-redirect route based on whether the user is logged in?

If there are other better ways to implement this flow, I would really appreciate the feedback. Thanks!

deepfriedbrain commented 1 year ago

I've resolved this by using session cookie. Closing this issue. Thanks!