Search code examples
phplaravelmulti-tenantlaravel-sanctumlaravel-lighthouse

Laravel Sanctum master key on multi tenant API


i'm trying to build a multi tenant API and so far my APIs are working great and i managed to implement multi-tenancy ( using archtechx/tenancy ), authentication with sanctum issuing keys is also working fine.

The application is structured such as there is a central domain example.com, the users that have access to this domain are called "Superadmins", they should be able to access with their API token (issued by sanctum on login) every other subdomain (or tenant) APIs with unrestricted access.

The tenants are on subdomains such as tenant.example.com and have personal databases, one for each tenant.

I was thinking about a couple of solutions to implement this:

  1. let the Superadmin Impersonate an admin of the tenant API and do stuff as that admin
  2. find a way to issue "Master keys" to superadmins that work on every tenant (subdomain)

I would lean towards the second solution because i find it more elegant. I've been searching the web for best practices for this kind of problem/feature but i haven't found anything that matches my question exactly.

In conclusion, is solution number 2 workable? And if so, is there a way to issue such "Master keys" with sanctum?

I'm using:

Laravel 8.48.1

Lighthouse-php as a framework to serve GraphQL through Laravel

Sanctum as Authentication guard

Tenancy for Laravel as a Multi-tenancy package


Solution

  • Master keys

    A simple thought: you could set token abilities for Sanctum tokens. Perhaps you could create the ability of master:access or something similar, that function as a Master key? You could grant super admins the master:access ability while creating the API token for them.

    This does require the tenant to access the master DB and authorize the ability of that specific key. I do not know the specific implementation of that package, but the Tenancy projects I worked with before provided easy access to the master DB. You could implement some kind of middleware or authorization to check if the user has a token with the master:access ability.

    Impersonating users

    Your other proposed solution of impersonating, also seems possible and is offered by the package according to the package documentation. This does require every tenant to have some kind of admin user. Since all Superadmins have access to the tenant over 1 shared admin user, I would not advise to go for this option.