p2-inc / keycloak-orgs

Single realm, multi-tenancy for SaaS apps
Other
362 stars 65 forks source link

Regognizing to which organization user is currently logged in #144

Closed yasiekz closed 7 months ago

yasiekz commented 7 months ago

Hello,

Let me describe some background

The use case

User X is logging into the system via KC. I want to have some value in access token which determines to which company (organization in KC) user is currently logged in. I've tried to use organization attributes and then map them to access token via organization attributes mapper, but it always ends up like this:

"company_id": {
    "d3ca0f95-9ee2-4052-87e0-16e62801ceae": {
      "name": "A",
      "attributes": {
        "employer_id": [
          "A_ID"
        ]
      }
    },
    "ffd53471-3d78-424b-8320-d6d9e47f72ff": {
      "name": "B",
      "attributes": {
        "id": [
          "B_ID"
        ]
      }
    }
  },

I see here every company to which user belongs to, which is not good, because when number of organizations grows - the size of acccess token will be grown accordingly. Also I have informations about every company, but I don't know to which company user is currently logged in.

Is there some approach you would recommend for me? I could do something with scopes or groups to archieve such result, but in that case organization feature from this plugin not usefull for me at all. Or maybe am I missing something, and the solutions is right before my eyes, but I'm too blind to see it :)

xgp commented 7 months ago

User may be logged in only to single company at the time

There is no such idea of "logged in" to an organization in this extension. This would be like asking which Keycloak "group" a user is logged into. The IAM system provides information about the user's identity, and isn't responsible for keeping track of application state.

I see here every company to which user belongs to, which is not good, because when number of organizations grows - the size of acccess token will be grown accordingly.

Correct. In the case where you plan to have a user in many/all organizations, don't map the organizations into the tokens. Instead, map it to the /userinfo endpoint. We also provide a /me API endpoint, which gives a list of all organizations that the user is a member and their roles in those organizations. Docs here https://phasetwo.io/api/get-me/

We recommend, and many customers are using this approach. They can then use the organization information to provide a switcher for the organization within their own application, storing state there.