Login to user's last used org without multiple login redirects

We’re facing an issue with trying to implement a login flow that always logs the user in to the last org they were using.

Our setup is that we let users be part of many organizations, but the flow for switching organizations is handled within our application and therefore we don’t want to send users to Auth0’s built-in org selection screen.

We are using the Next.js SDK and have a middleware around the app for handling auth with it.

What we currently do:
Log the user in without an org (Next.js middleware directs user to /api/auth/login and back again)

On the next (authenticated) request for the page, check their user metadata for a special property we are storing that represents their last-used org id (in the middleware)

Redirect the user to ‘/api/auth/login’ again with that org id. They already have a valid login so the re-auth is handled silently with no further input. Now the user’s session is authenticated with that org.

They land back in the middleware again after all these redirects are finished and their token has an org_id. Now we can serve the original page they requested.

We have a custom post-login flow which stores the org id being logged into (if there is one) in that metadata field, so that it is kept up to date.

We also have special logic in our application to handle when the last-used org is not set, in which case we hit the Auth0 management API to get the list of orgs for that user and then log them in to the first one.

Problems with this:

  • need to log user in without an org to find out what org we should log them in to, requiring two redirects and making login take much longer
  • last-used org id needs to be kept up-to-date by our own code we have to maintain
  • a user being removed from an org or that org being deleted means our org-login redirect needs to account for and handle errors with the user not being able to log in with that org id. That also means we need to make sure the bad id gets cleared from metadata storage in these cases.

More Ideal Solution
If possible, it would be great if we could handle logging them into the org via the post-login flow somehow. Basically the logic would be:

  • they log in without an org from our application
  • action in the flow reads user metadata to find that last-used org
  • action handles re-authenticating them with that org id, or clears it if that fails

Most ideal solution
A perfect solution for our use case would be if Auth0 just supported the concept of a “last known org” out of the box and allowed the application to specify that the user should be automatically logged in to that organization without having it be specified. It would also handle cases where they were removed from their last org or it was deleted by simply logging them into the first one.