Role Template with reference to metadata property from Open ID Realm

Hello,
we are having SSO solution implemented based with Keycloak and based on OpenID concept
It is working well and we are able to assign roles by username or with reference to realm.name

As a next step I want to implement role mapping based on some metadata properties assigned to user in Keycloak. The value is added to user details and passed as part of the authorisation JWT token:

{
  "exp": 1684484836,
  "iat": 1684484536,
  "jti": "f293f1ae-d364-483a-9d5f-019dccd8d4c3",
  "iss": "https://sso.<redacted>",
  "aud": "account",
  "sub": "<redacted>",
  "typ": "Bearer",
  "azp": "backend",
  "session_state": "76182e18-20e5-490a-a417-5d451d75b63e",
  "acr": "1",
  "allowed-origins": [
    "/*"
  ],
  "realm_access": {
    "roles": [
      "default-roles-sas",
      "REPORT_MANAGER",
      "offline_access",
      "uma_authorization"
    ]
  },
  "resource_access": {
    "account": {
      "roles": [
        "manage-account",
        "manage-account-links",
        "view-profile"
      ]
    }
  },
  "scope": "profile backend-client-scope email",
  "sid": "<redacted>",
  "tenant_id": "Sim2",
  "email_verified": true,
  "name": "<redacted>Surname",
  "preferred_username": "<redacted>",
  "given_name": "<redacted>",
  "family_name": "<redacted>",
  "email": "<redacted>"
}

Note that we have in token attribute tenant_id (at the very bottom of the list) that I want to use when assigning role in role template.

How shall I reference this attribute in role mapping rules and in role template?

From documentation I understood it shall be referenced as 'metadata.tenant_id' but when I try to apply it in simple rule it does not applied.

My current role mapping template (not working):

{
  "keycloak_tenant": {
    "enabled": true,
    "role_templates": [
      {
        "template": """{"source":"azv_logs"}""",
        "format": "string"
      }
    ],
    "rules": {
      "all": [
        {
          "field": {
            "realm.name": "oidc1"
          }
        },
        {
          "field": {
            "metadata.tenant_id": "*"
          }
        }
      ]
    },
    "metadata": {}
  }
}

In case someone will stuck on it as well -- after testing several variants I figured out that correct notion would be metadata.oidc(tenant_id)

E.g. mapping rule:

{
  "keycloak_tenant": {
    "enabled": true,
    "role_templates": [
      {
        "template": """{"source":"{{metadata.oidc(tenant_id)}}_logs"}""",
        "format": "string"
      }
    ],
    "rules": {
      "all": [
        {
          "field": {
            "metadata.oidc(tenant_id)": "*"
          }
        }
      ]
    },
    "metadata": {}
  }
}

also note that same notion is used in role template value: {{metadata.oidc(tenant_id)}}_logs

Best Regards, Artem

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.