While your approach is conceptually sound for managing multi-tenancy, it's important to note that Ory Kratos, which is part of Ory Identities, does not natively support multi-tenancy in a self-hosted setup. According to the [Ory documentation on multitenancy](
https://www.ory.sh/docs/kratos/guides/multi-tenancy-multitenant): "Ory Network is the only available option to have a multi-tenant Ory Kratos set up. It is not possible to self-host Ory Kratos as a multi-tenant service as its data model does not support this due to data, scalability, and operational complexity." However, if you're using Ory Network, which does support multi-tenancy, your approach of maintaining an active tenant ID in the user's identity metadata could be a viable solution. Here are some considerations based on the available Ory documentation: 1.
Identity Metadata: Ory Identities supports storing metadata for identities. You could use this feature to store the active tenant ID. As described in the [Identity metadata & traits documentation](
https://www.ory.sh/docs/kratos/manage-identities/managing-users-identities-metadata), there are two types of metadata: public and admin. The active tenant ID could be stored in the public metadata if you need to access it from the frontend, or in the admin metadata if it should only be accessible through admin APIs. 2.
Session Management: When a user logs in or switches tenants, you would need to update the identity metadata and potentially issue a new session. Ory provides session management capabilities as described in the [Session management overview](
https://www.ory.sh/docs/kratos/session-management/overview). 3.
JWT Integration: While Ory Kratos primarily uses session cookies or tokens, it's possible to convert an Ory Session to a JWT. This is mentioned in the session management documentation: "You can also convert an Ory Session to a JWT, read more about this approach here." This could be useful for including the active tenant ID in a JWT for your backend services. 4.
Custom Logic: To implement the tenant switching and scoping logic, you might need to use [Ory Actions](
https://www.ory.sh/docs/identities/sign-in/actions) or integrate with your own backend services. While this approach could work, it's important to note that implementing multi-tenancy correctly and securely can be complex. The Ory documentation doesn't provide specific guidance on implementing this exact scenario, so you would need to carefully design and test your solution to ensure it meets your security and functionality requirements. If you're considering using Ory for a multi-tenant application, it's recommended to use Ory Network, which is designed to handle multi-tenancy scenarios out of the box. For more specific guidance on implementing multi-tenancy with Ory, you might want to contact Ory directly or consult with their support team.