API: Using basic auth and switching organization dynamically

Here’s the scenario I’m building: I’m embedding Grafana into a web site that will face multiple external users that belong to different organizations. I fetch and return a list of dashboards to the client for the organization the current user belongs to.

Since API keys are per organizations and most API resources are retrieved by API key context, I need to somehow find the API key for the user’s organization or else access the dashboard by specific organization ID or similar.

What I’ve tried so far is to use basic auth using my root Grafana admin user and set the org context to the users organization. Something along these lines:

  1. Get logged in user:
    curl http://admin:admin@localhost:3000/api/users/lookup/<logged in user email>

  2. Set the context for the admin user to the user’s org ID:
    curl -X POST http://admin:admin@localhost:3000/api/user/using/<id of user org>

  3. Get the dashboards for the current organization:
    curl http://admin:admin@localhost:3000/api/search

However, issues will arise since there will be many users logged in and sending requests concurrently so I can’t expect that the organization context will be persisted between the requests (another user might have changed it meanwhile).

Is there any other way of solving this use case or do I have to store the relationship between users and API keys somewhere else?