How do companies handle authentication in their multi-tenant web apps?
Essentially I have a single PostgreSQL database instance with many tables. Each table has a workspace_id column which I will use to use to grant/deny access. You can think of a workspace as a client and a single user can be associated with multiple workspaces.
My initial thought was to:
jwt token containing the user details and the workspace id.I am halfway through implementing what I've described above but I am not sure if that's the best approach. What do you think?
I'm not sure I would call this multi-tenancy - really it is just a case of different users with different claims:
When your UI calls APIs, the back end should receive a JWT access token with either of these payloads. The second of these is preferred, but not all systems support that:
SIMPLEST OPTION
This might just be to look up the user's workspace IDs whenever an API request is received, based on the user ID in the JWT access token, as in Joe's comment above.
CLAIMS PRINCIPAL
If workspace IDs are used frequently for authorization across many API requests, then a better option is to design a Claims Principal object, containing data commonly used by the API for authorization, and containing the important IDs. It might look like this for a particular user:
{
sub: "wdvohjkerwt8",
userID: 234,
workspaceIDs: [2, 7, 19]
}
This object typically needs to be comprised of both Identity Data (stored by the Authorization Server) and also domain specific data. The above userID might be a database key, whereas the subject claim is often a generated value.
When an API request is received, you can either read all claims from the JWT access token, or combine domain specific data with the JWT data.
The Claims Principal is then injected where needed, so that your API authorization logic can be coded in a simple way. In your case this will involve filtering workspaces when working with collections, or denying access if the user specifically tries to access a workspace they are not entitled to.
Here is some sample Node.js code of mine that does this, using a region array claim: