Skip to content

Module Integration with IAM

This document explains integration topics for modules connecting with the IAM Module, including endpoint registration, permissions, client configuration, and token exchange requirements.

Overview

Modules integrate with the IAM Module through a comprehensive system that includes:

This integration enables modules to participate in the platform's centralized identity and access management while maintaining their own domain-specific roles and data.

Integration Message Structure

Modules send Hub Integration Messages to register endpoints and clients with the IAM Module.

For complete details about the message structure and schemas, see Messaging Documentation.

Message Format

{
    "message": {
        "version": 1,
        "id": "11111111-2222-3333-4444-555555555555",
        "relatedId": "",
        "applicationId": "mock-module",
        "dateTime": "2025-09-18T12:00:00Z"
    },
    "integration": {
        "type": "registration",
        "endpoints": [
            {
                "purpose": "getRoles",
                "uri": "https://mock-module.example.local/api/roles",
                "boundary": "internal",
                "permissions": [
                    {
                        "roles": {
                            "access": ["reader", "writer"]
                        },
                        "context": {
                            "entities": ["E1"],
                            "entityGroups": []
                        }
                    }
                ]
            }
        ]
    }
}

What is applicationId?

It uniquely identifies your module across the platform. It's used for:

  • Creating the scope for your module's permissions
  • Routing response messages back to your module
  • Generating default client IDs ({applicationId}-module-client)

Note

ApplicationId cannot contain ::

Endpoint Purposes

The IAM Module recognizes three endpoint purposes for integration. Understanding the distinction between module context and global context is essential for proper integration.

For detailed API specifications for each endpoint, see Endpoint API Specifications.

getRoles

Provides module-specific roles that the IAM Module should fetch and manage.

When to use: Your module exposes roles that need to be available for assignment in the IAM system. This is for module context - roles that are specific to your module's functionality.

Example: A data collection module registering roles like "report_editor", "corep", "finrep"

API Details: See getRoles Endpoint for request/response specifications.

getEntities

Provides globally visible entities that are consumed across the platform.

When to use: Your module is the source of entity data (typically the Master Data Management module). This represents global context - entities that are shared across the platform, not module-specific roles.

Important: Only one module can provide global entities at a time. When a new module registers global context, it replaces the previous registration.

API Details: See getEntities Endpoint for request/response specifications.

getEntityGroups

Provides globally visible entity groups that are consumed across the platform.

When to use: Your module supplies entity group definitions (typically the Master Data Management module). This represents global context - entity groups that are shared across the platform, not module-specific roles.

Important: Only one module can provide global entity groups at a time. When a new module registers global context, it replaces the previous registration.

API Details: See getEntityGroups Endpoint for request/response specifications.

Message Fields

type

  • Must be registration to create/update endpoints or deregistration to remove all of them
  • Required field

endpoints

  • Required for registration messages
  • Array of endpoint definitions
  • If an endpoint was registered before but is not present in the new registration message, it will be removed

Important: Re-registration replaces your module's entire endpoint list. If you previously registered 3 endpoints and send a new registration with only 2, the missing endpoint is automatically deregistered. Always include all endpoints you want to keep active.

uri

  • Required for endpoints in registration messages
  • Must point to the provider API endpoint for the indicated purpose
  • Must be a valid URI

boundary

  • May be internal or external
  • If omitted, defaults to internal
  • Only IAM instances with a matching boundary will process this specific endpoint
  • See Boundary Filtering for more details on how boundaries are processed

What is a boundary?

A boundary represents the deployment context of an IAM instance:

  • internal: For internal-facing applications (e.g., Supervision Centre for bank supervisors)
  • external: For external-facing applications (e.g., Portal for bank users)

Example: If your module has endpoints that should only be accessible to the internal IAM (Supervision Centre), set boundary: "internal". The external IAM (Portal) will ignore this endpoint registration.

permissions

  • An array of permission objects that define the permissions granted to IAM instances for calling this endpoint
  • Each permission object uses the structured role format: {"roles": {"typeName": ["roleId1", "roleId2"]}, "context": {"entities": [...], "entityGroups": [...]}}
  • Format Requirement: The roles object is a dictionary where keys are typeName values from your module's getRoles response, and values are arrays of role IDs belonging to that type
  • All permissions throughout the system use this format - in storage, tokens, APIs, and messages (see IAM Roles and Permissions Model)
  • Permissions are created in the scope of the module specified in the applicationId
  • Assigned to the IAM instance that processes the registration
  • If empty array, null, or omitted, the endpoint is considered unauthorised and no permissions are assigned
  • See Endpoint Permissions for complete details on how these permissions work

What is "module scope"?

When permissions are created in your module's scope, it means:

  • The roles (e.g., reader, writer) must exist in your module, not in IAM - use role IDs from your own module's getRoles endpoint
  • When IAM exchanges tokens, it receives permissions to act as a user with those roles in your module
  • Example: If applicationId: "data-collection" and permissions: { roles: ["reader"] }, the IAM gets the reader role in the data-collection module's context

Endpoint Registration and Lifecycle

Registration Process

When a module sends a registration message:

Message-Level Filtering:

The entire registration message is skipped if: - (No client OR client boundary mismatched) AND (No endpoints OR all endpoints boundary mismatched)

This means at least one of the following must be true for the message to be processed: - Client section exists and its boundary matches the IAM instance's boundary - At least one endpoint exists with a boundary matching the IAM instance's boundary

If neither condition is met, the registration message is silently ignored by this IAM instance.

Processing Steps:

  1. Boundary Filtering: IAM checks if the endpoint's boundary matches the IAM instance's configured boundary
  2. Endpoint Processing: Endpoints are created or updated based on the purpose and uri
  3. Permission Assignment: If permissions are provided, they are assigned to the IAM service account
  4. Response: IAM sends a response message back to the module (see Registration Response Flow)

Permission Lifecycle

  • On Registration: Endpoint permissions are added to the system and assigned to the IAM instance for the module applicationId
  • On Reregistration: New permissions are added, but old permissions for the endpoint are NOT unassigned or removed
  • On Deregistration: Permissions are unassigned (not removed from the IAM system)
  • Global Context Special Behavior: When global context (getEntities, getEntityGroups) is registered for moduleA, and new global context is registered for moduleB, the global context is overridden with new URI and new module name (applicationId), and permissions for moduleA that were assigned during moduleA global context registration are unassigned

Deregistration

Setting type to deregistration removes:

  • All registered endpoints for the module
  • Permission assignments (but not the permissions themselves)
  • The module's representation from the IAM system

Endpoint API Specifications

All module endpoints must follow specific requirements to ensure proper integration with the platform.

Common Requirements for All Endpoints

HTTP Method

All module endpoints must use the POST method, not GET. This is required because:

  1. The IAM platform sends the requesting user's permissions in the request body
  2. Permissions required for endpoint access are assigned to the client that is the subject of the token in the Authorization header
  3. Query parameters (query and ids) can be used in addition to the body permissions

Request Body Format

The IAM platform will send a POST request with the user's effective permissions and groups in the request body:

{
  "userPermissions": [
    {
      "module": "mock-module",
      "permissions": [
        {
          "roles": {
            "access": ["reader", "writer"]
          },
          "context": {
            "entities": ["E1"],
            "entityGroups": []
          }
        }
      ]
    }
  ],
  "userGroups": ["administrator", "testGroup"]
}

Search and Filtering (Query Parameters)

All module endpoints must support these query parameters. Both parameters can be used together on the same request.

  • ?query=<searchterm> - Searches across all fields in the objects
  • ?ids=<id1>,<id2>,<id3> - Returns only objects with the specified IDs

getRoles requests also receive an optional language tag:

  • ?locale=<BCP-47> - Preferred language for role label / type labels (for example en-GB or de-DE). IAM always sends this parameter. Providers that support translations should return localized strings; providers that do not may ignore it and return their default text.

Token Exchange Requirement

Critical

All module endpoints MUST implement token exchange. Incoming tokens do NOT contain custom permissions - they must be obtained via token exchange. Additionally, if your client will exchange tokens from IAM's client, ensure your client is added to IAM's client audiences as described in Manual Client Creation step 5. For automatic client creation it is done automatically.

Why is this a two-step process?

  1. Request body permissions tell your endpoint what data to return (filter by user's permissions)
  2. Token exchange permissions verify the caller (IAM) has permission to call your endpoint at all

Both checks are necessary: the first ensures users only see their data, the second ensures only authorized clients can call your endpoint.

See Token Usage and Exchange Requirements for complete implementation details and audience configuration.

Module Implementation Checklist

Your module endpoints must:

  1. Accept POST requests with Content-Type: application/json
  2. Receive IAM's client token in the Authorization header (without custom permissions)
  3. Exchange the token to obtain custom permissions and verify the IAM client has the necessary permissions to access your endpoint
  4. Parse the permissions array from the request body
  5. Filter your response data based on the provided permissions (optional - but recommended to respect user's access scope)
  6. Support query parameters (query and ids) in addition to the body permissions; for getRoles, also accept optional locale (ignore it if you do not translate labels)
  7. Return responses with the correct schema

Why filter responses? When IAM calls your getRoles endpoint with a specific user's permissions in the request body, you should return only the roles that user can see/manage. This allows IAM to build accurate UIs showing what each user can access. If you don't filter, users might see roles they can't actually use.

getRoles Endpoint

Purpose: Returns module-specific roles that should be available for assignment in the IAM system.

Context: This endpoint handles module context (module-specific roles). See Endpoint Purposes - getRoles for when to use this purpose.

Model Reference: The complete structure, semantics, and dependency rules for roles, types, and dependencies are documented in IAM Roles and Permissions Model. That document explains the generic model that applies to all modules.

Endpoint Requirements:

  • Must return a JSON response with roles, types, and dependencies arrays (dependencies can be empty)
  • Role typeName values must match types.typeName
  • Results should be filtered by the requesting user's permissions (sent in the request body)
  • The endpoint shall return only those roles that the user triggering the API call has permissions to manage
  • Must implement token exchange and support query parameters

Response Schema:

{
  "roles": [
    {
      "id": "string (required)",
      "label": "string (required)",
      "typeName": "string (required)",
      "parentId": "string (optional)"
    }
  ],
  "types": [
    {
      "typeName": "string (required)",
      "label": "string (required)",
      "selector": "checkbox|dropdown|recordset (required)",
      "showInitially": "boolean (required)",
      "group": "string (optional)"
    }
  ],
  "dependencies": [
    {
      "when": { "item": { "typeName": ["roleId"] } },
      "then": { "item": { "typeName": ["*"] }, "constrain": { "min": 1, "max": 3 } }
    }
  ]
}

Response Example:

{
  "roles": [
    {
      "id": "reportViewer",
      "label": "Report Viewer",
      "typeName": "access"
    },
    {
      "id": "datasetA",
      "label": "Dataset A",
      "typeName": "scope"
    }
  ],
  "types": [
    {
      "typeName": "access",
      "label": "Access",
      "selector": "checkbox",
      "showInitially": true
    },
    {
      "typeName": "scope",
      "label": "Scope",
      "selector": "recordset",
      "showInitially": false
    }
  ],
  "dependencies": [
    {
      "when": { "item": { "access": ["reportViewer"] } },
      "then": { "item": { "scope": ["*"] }, "constrain": { "min": 1 } }
    }
  ]
}

getEntities Endpoint

Purpose: Returns globally visible entities consumed across the platform.

Context: This endpoint handles global context (platform-wide entities). See Endpoint Purposes - getEntities for when to use this purpose and important limitations.

Endpoint Requirements:

  • Must return a list of all entities
  • Results should be filtered by the requesting user's permissions (sent in the request body)
  • The endpoint shall return only those entities that the user triggering the API call has permissions to manage
  • Must implement token exchange and support query parameters

Response Schema:

{
  "entities": [
    {
      "id": "string (required)",
      "name": "string (required)"
    }
  ]
}

Response Example:

{
  "entities": [
    {
      "name": "HSBC Bank",
      "id": "1"
    },
    {
      "name": "Barclays",
      "id": "2"
    }
  ]
}

getEntityGroups Endpoint

Purpose: Returns globally visible entity groups consumed across the platform.

Context: This endpoint handles global context (platform-wide entity groups). See Endpoint Purposes - getEntityGroups for when to use this purpose and important limitations.

Endpoint Requirements:

  • Must return a list of all entity groups
  • Results should be filtered by the requesting user's permissions (sent in the request body)
  • The endpoint shall return only those entity groups that the user triggering the API call has permissions to manage
  • Must implement token exchange and support query parameters

Response Schema:

{
  "entityGroups": [
    {
      "id": "string (required)",
      "name": "string (required)",
      "parentId": "string (optional)"
    }
  ]
}

Response Example:

{
  "entityGroups": [
    {
      "name": "Banking",
      "id": "1"
    },
    {
      "name": "Insurance",
      "id": "3"
    },
    {
      "name": "Big Banks",
      "id": "4",
      "parentId": "1"
    }
  ]
}

Endpoint Permissions

Endpoint permissions inform the IAM what permissions it needs to assign to itself to be able to access your module's registered endpoints. These permissions are verified during token exchange when IAM calls your endpoints.

See also: Client vs Endpoint Permissions to understand the difference between these two permission types.

How Endpoint Permissions Work

When you register an endpoint with permissions (as shown in the Integration Message Structure):

  1. Permissions are created in the scope of your module (specified in applicationId)
  2. Permissions are assigned to the IAM service account that processes the registration
  3. Direction: IAM → Module (IAM calls your module endpoints)
  4. Verification: When IAM calls your endpoint, you must exchange the token to verify IAM has these permissions

Example:

{
  "purpose": "getRoles",
  "uri": "https://mock-module.example.local/api/roles",
  "permissions": [
    {
      "roles": {
        "access": ["reader", "writer"]
      },
      "context": {
        "entities": ["E1"],
        "entityGroups": []
      }
    }
  ]
}

This grants the IAM service account the reader and writer roles in your module's scope, allowing IAM to call your getRoles endpoint.

Permission Structure

Each object in the permissions array has the following structure:

roles (required):

  • Dictionary of role type -> role IDs
  • Keys must match your module's typeName values from getRoles
  • Role IDs must exist in your module
  • IAM will have these roles when calling your endpoint

context (optional):

  • entities: Array of entity IDs that scope the permission to specific entities
  • entityGroups: Array of entity group IDs that scope the permission to specific entity groups

Super Admin Functionality

During IAM initialization, the default admin user (configured via adminUsername in values.yaml) is automatically assigned the super_admin role for the IAM module.

When the IAM sends requests to module endpoints, the request body includes all user permissions from both the target module and the IAM module.

Module Implementation:

  • Modules should return all available data when the requesting user has the super_admin role in the IAM module
  • This applies to all endpoint types: getRoles, getEntities, and getEntityGroups
  • Modules may optionally implement a toggle to disable super admin functionality after their own administrators are configured

Registration Response Flow

When a module sends a registration message to the IAM Module, the IAM Module processes the registration and sends back a response message.

Response Message Characteristics

  • Subject: The response message uses module-specific subjects with hub.integration as base by appending the recipient's applicationId (Example: hub.integration.examplemodule) - as defined in the Messaging Documentation
  • Related Message: The response message includes a relatedId field in the message section that references the id of the original registration message
  • Content: The integration object in a response contains only type (set to "registration") and response fields - it does not include endpoints or client information
  • Configuration: The response object provides essential IAM Module configuration including API URLs and Keycloak settings
  • Sender: Only the IAM Module sends messages with the response field populated
  • Recipient: The registration response message should be processed only by the module that sent the original registration message

Important: Modules must subscribe to hub.integration.<applicationId> to receive these responses.

Response Message Example

{
  "message": {
    "version": 1,
    "id": "7b8c9d2e-4f5a-6b7c-8d9e-0f1a2b3c4d5e",
    "relatedId": "40009a87-fc31-49ff-88fb-707a7475150b",
    "applicationId": "IAMModule",
    "dateTime": "2025-08-13T14:30:15Z"
  },
  "integration": {
    "type": "registration",
    "response": {
      "iamModuleApplicationId": "IAM-Module",
      "boundary": "internal",
      "apiBaseUrl": "https://main.portal.rsh-iam.dev.suptech.regnology.io/api",
      "clusterInternalApiBaseUrl": "http://iam-module-api.iam.svc.cluster.local:8080/api",
      "iamModuleSuperAdminRoleId": "super_admin",
      "keycloakBaseUrl": "https://main.portal.rsh-iam.dev.suptech.regnology.io/auth",
      "clusterInternalKeycloakBaseUrl": "http://keycloak.iam.svc.cluster.local:8080/auth",
      "keycloakRealm": "platform-realm",
      "clientId": "masterdata-module-client"
    }
  }
}

Response Object Fields

Field Name Description
iamModuleApplicationId The application ID of the IAM Module
boundary The boundary context for which this response applies (e.g., "external" for portal, "internal" for supervision center)
apiBaseUrl The externally accessible base URL for the IAM Module API
clusterInternalApiBaseUrl The cluster-internal base URL for the IAM Module API, used for service-to-service communication within the Kubernetes cluster
iamModuleSuperAdminRoleId The role ID for the super administrator role in the IAM Module
keycloakBaseUrl The externally accessible base URL for the Keycloak authentication server
clusterInternalKeycloakBaseUrl The cluster-internal base URL for Keycloak, used for service-to-service authentication within the Kubernetes cluster
keycloakRealm The Keycloak realm name that the module should use for authentication and authorization
clientId The OAuth2/OIDC client ID created for the registering module (optional, can be derived from applicationId)

Using the Response

The response enables modules to automatically configure themselves with the correct IAM endpoints and credentials after registration completes. The response is sent asynchronously; failures don't affect the registration flow itself.

Encrypted Client Secret Delivery

IAM supports secure delivery of a Keycloak client secret to a registering module. The secret is never sent in plaintext — it is encrypted using an RSA public key provided by the module during registration, so only the module (which holds the corresponding private key) can decrypt it.

To receive an encrypted client secret in the registration response, a module must satisfy both of the following conditions in its registration message:

  • Include a client section describing the Keycloak client to register
  • Include its RSA public key in the integration.config.values array under the key "publicKey"

If either condition is not met, the config section will be absent from the registration response entirely.

Step 1: Generate an RSA Key Pair

The module must generate a 2048-bit (or stronger) RSA key pair. The private key must be securely stored by the module and never transmitted. Only the public key is sent to IAM.

The public key must be exported in SubjectPublicKeyInfo DER format and then base64-encoded into a single-line string. PEM format (i.e. the format with -----BEGIN PUBLIC KEY----- headers and line breaks) is not accepted — IAM expects raw base64 DER only.

Step 2: Include the Public Key in the Registration Message

The base64 DER public key must be passed in integration.config.values alongside the client section in the registration message:

{
  "message": {
    "id": "...",
    "applicationId": "my-module",
    ...
  },
  "integration": {
    "type": "registration",
    "client": {
      "clientId": "my-module-client",
      "boundaries": ["internal"],
      ...
    },
    "config": {
      "values": [
        {
          "key": "publicKey",
          "value": "<base64-DER-encoded RSA public key>"
        }
      ]
    },
    "endpoints": [ ... ]
  }
}

Note: Both the client section and the publicKey config value are required. If the client section is absent, or the client cannot be registered (e.g. due to a boundary mismatch or a Keycloak error), IAM will not include any client secret in the response, regardless of whether a public key was provided.

Step 3: IAM Processes the Registration and Encrypts the Secret

Upon receiving the registration message, IAM performs the following steps:

  1. Processes the client section — finds the existing Keycloak client or creates a new one
  2. Retrieves the Keycloak client secret for the registered client
  3. Encrypts the client secret using the RSA public key from the message with the following parameters:
  4. Algorithm: RSA-OAEP (Optimal Asymmetric Encryption Padding)
  5. Hash function: SHA-256
  6. Key format: SubjectPublicKeyInfo DER, base64-decoded from the publicKey config value
  7. Output: base64-encoded RSA-OAEP ciphertext
  8. Includes the encrypted secret in the registration response

Step 4: Retrieve the Encrypted Secret from the Response

The encrypted client secret is returned in the registration response message under integration.config.values, with the key "encryptedClientSecret":

{
  "message": {
    "id": "...",
    "applicationId": "iam",
    "relatedId": "<id of the original registration message>",
    ...
  },
  "integration": {
    "type": "registration",
    "response": {
      "clientId": "my-module-client",
      ...
    },
    "config": {
      "values": [
        {
          "key": "encryptedClientSecret",
          "value": "<base64-encoded RSA-OAEP ciphertext>"
        }
      ]
    }
  }
}

If the response does not contain a config section, or config.values does not contain the "encryptedClientSecret" key, it means one of the required conditions was not met. See the Conditions section below.

Step 5: Decrypt the Secret

The module decrypts the "encryptedClientSecret" value using its RSA private key with the following parameters:

  • Algorithm: RSA-OAEP
  • Hash function: SHA-256 (used for both the OAEP label hash and the MGF1 mask generation hash)
  • Key: the RSA private key corresponding to the public key sent in the registration message

Conditions

All of the following conditions must be true for the encrypted client secret to be included in the registration response:

Condition If not met
client section is present in the registration message config is omitted from the response
Client boundary matches IAM's configured boundary config is omitted from the response
Client is successfully found or created in Keycloak config is omitted from the response
publicKey is present in integration.config.values config is omitted from the response; IAM logs an info message
Client secret is successfully retrieved from Keycloak config is omitted from the response; IAM logs a warning
RSA encryption succeeds config is omitted from the response; IAM logs an error

Token Usage and Exchange Requirements

Critical

All inter-component communication MUST use tokens WITHOUT custom permissions in the Authorization header.

Token Exchange Audience Configuration

If you create a client (manually or via the automated registration endpoint) that will be used to exchange tokens initially requested by IAM's client, then your client's clientId must be added as an audience to the IAM's client. Otherwise, token exchange will fail. See Manual Client Creation in Keycloak step 5 for details.

Why This Is Critical

Custom permissions claims can grow extremely large (15KB+) as modules register more permissions, causing:

  • HTTP header size limits exceeded (IIS blocks requests)
  • Network performance degradation
  • Gateway and proxy failures

Implementation Requirements

For ALL communication scenarios:

  • Module-to-module communication
  • Backend-frontend communication
  • Machine-to-machine communication
  • IAM API calling module endpoints (getRoles, getEntities, getEntityGroups)

You MUST:

  1. Send requests with tokens WITHOUT custom permissions in the Authorization header
  2. Recipient must exchange the received token for one WITH custom permissions using Standard Token Exchange (RFC 8693)
  3. Use the exchanged token (with custom permissions) only for internal authorization decisions, NOT in subsequent HTTP requests

Token Exchange Implementation

When your module receives a request:

# Step 1: Receive request with token (no custom permissions)
Authorization: Bearer <incoming_token_without_custom_permissions>

# Step 2: Exchange token to get custom permissions
POST https://<keycloak-url>/realms/<realm>/protocol/openid-connect/token
Content-Type: application/x-www-form-urlencoded

grant_type=urn:ietf:params:oauth:grant-type:token-exchange
&client_id=<your_module_client_id>
&client_secret=<your_client_secret>
&subject_token=<incoming_token_without_custom_permissions>
&subject_token_type=urn:ietf:params:oauth:token-type:access_token
&requested_token_type=urn:ietf:params:oauth:token-type:access_token
&scope=custom-permissions_token-exchange

# Step 3: Use exchanged token (with custom_permissions) for authorization decisions
# DO NOT send this token in Authorization headers to other services

Example: Complete Flow

Let's say IAM calls your module's getRoles endpoint:

  1. IAM sends request:

    POST https://your-module.example.com/api/roles
    Authorization: Bearer eyJhbGc...(token WITHOUT custom_permissions)
    Content-Type: application/json
    
    {"userPermissions": [...], "userGroups": [...]}
    

  2. Your module receives token - if you decode it, you'll see it has basic claims but NO custom_permissions field

  3. Your module exchanges the token:

  4. Sends token exchange request to Keycloak with your client credentials
  5. Keycloak validates: Is the incoming token valid? Is your client allowed to exchange it? (audience check)
  6. Returns new token

  7. Exchanged token contains custom_permissions:

    {
      "custom_permissions": [
        {
          "module": "your-module",
          "permissions": [
            {
              "roles": {
                "access": ["reader", "writer"]
              },
              "context": {
                "entities": ["E1"]
              }
            }
          ]
        }
      ]
    }
    

  8. Your module verifies: Does the caller have the required permissions (matching the endpoint permissions you registered)?

  9. Your module responds with the filtered data based on permissions in the request body

IAM API Behavior

When IAM API sends requests to module endpoints (getRoles, getEntities, getEntityGroups):

  1. Authorization header contains IAM's client token without custom permissions
  2. The IAM client has the required permissions assigned to its service account to access your endpoint (configured via endpoint permissions during module registration)
  3. Permissions are NOT included in the token - they must be obtained via token exchange
  4. Your module must exchange the token to verify the IAM client has the necessary permissions
  5. Your client must be configured as an audience in IAM's client for token exchange to succeed (see Manual Client Creation step 5)

This is mandatory for all modules - failure to implement token exchange or configure audiences correctly will result in authorization failures.

Token Invalidation and Caching Considerations

Important

When user permissions are changed (added, removed, or modified) in the IAM, the user's active sessions are invalidated, and they must obtain a new token. However, if modules cache access tokens, there may be a brief period where cached tokens with outdated permissions could still be used.

Security enforcement: The IAM backend always enforces up-to-date permissions regardless of token state. Even if a module uses a cached token with stale permissions, the IAM API will validate against the current permission set.

Module caching recommendations:

  • Keep token cache duration below 5 minutes to maintain a consistent permission enforcement latency across the platform
  • Be aware that cached tokens may contain outdated custom_permissions claims
  • Consider implementing cache invalidation mechanisms if immediate permission updates are critical for your module's security model
  • The IAM maintains a 5-minute permission cache internally, so aligning module token caches with this duration provides consistent behavior

Client Registration

OAuth clients enable your module to authenticate with IAM and make API calls.

Related Documentation

This section covers programmatic client registration during module integration. For declarative client configuration using values.yaml (including redirect URIs, CORS settings, and other Keycloak properties), see:

You can create clients using three methods:

  1. Automated registration via Hub Integration Message (recommended)
  2. Via IAM API endpoint
  3. Manual creation in Keycloak

Which method should I use?

  • Hub Integration Message: Use when your module already sends integration messages for endpoint registration. This keeps all registration in one place and handles boundaries automatically.
  • IAM API Endpoint: Use for quick setup during development, or when you need to create clients programmatically without integration messages.
  • Manual Keycloak: Use only when you need custom client configuration that the automated methods don't support (rare cases). IAM API offers also generic endpoints for client creation.
  • Configuration Files (values.yaml): Use for declarative client configuration, customizing redirect URIs, CORS settings, or adding development users/roles. Chart-managed IAM client URLs belong under keycloak.clientUrls. Additional clients: Extending Keycloak Configuration.

Client vs Endpoint Permissions

Understanding the distinction between client and endpoint permissions is critical for proper integration. See Endpoint Permissions for more details on endpoint permissions.

Aspect Client Permissions Endpoint Permissions
Assigned to Client's service account IAM's service account
Module scope IAM module Sending module
Role source Use IAM module's roles Use your module's roles
Purpose Module calls IAM API IAM calls module endpoints
Direction Module → IAM IAM → Module
Lifecycle Persist until client deleted Unassigned on endpoint deregistration

Important:

  • Client permissions must use role IDs from the IAM module's getRoles endpoint (e.g., IAM roles like action, resource, module, group)
  • Endpoint permissions must use role IDs from your own module's getRoles endpoint (e.g., your module-specific roles)

Example scenario:

  • Your module's client permissions allow it to read user data from IAM API
  • Your module's endpoint permissions allow IAM to fetch roles from your getRoles endpoint
  • Both are needed for bidirectional communication

Automated Client Registration via Hub Integration Message

Modules can automatically create and configure OAuth clients by including a client object in the Hub Integration Message. This provides a streamlined alternative to manual client creation via the API or Keycloak UI.

Registration Flow

When a Hub Integration Message includes a client object, the IAM performs the following actions:

Registration (type: "registration"):

  1. Boundary Filtering:

    • IAM checks if any of the client's boundaries match the IAM instance's configured boundary
    • If boundaries is empty or omitted, it defaults to ["internal"]
    • If no boundaries match, the client registration is silently skipped
    • Multiple boundaries can be specified to register the client in multiple IAM instances
  2. Client Identification:

    • Uses the specified clientId or generates {applicationId}-module-client if not provided
    • Queries Keycloak to check if the client already exists
  3. Client Creation or Update:

    • New client: Creates a module client with standard OAuth configuration
    • Existing client: Updates the existing client's configuration
    • Both scenarios result in the same final configuration
  4. URL Configuration:

    • Updates all URL fields from the message: rootUrl, baseUrl, adminUrl, redirectUris, webOrigins
    • URLs can be null or omitted if not needed for the module's OAuth flow
  5. Module Client Configuration Applied:

    • Service account enabled (for machine-to-machine communication)
    • Standard flow enabled (authorization code flow)
    • Direct access grants enabled (resource owner password credentials)
    • Standard Token Exchange enabled (RFC 8693 for token exchange)
    • Confidential client (requires client secret, not public)
  6. Permission Assignment:

    • If permissions array is provided, each permission object is assigned to the client's service account
    • Permissions are always scoped to the IAM module (not the module sending the message)
    • Allows the client to call IAM API endpoints with proper authorization
    • Permissions persist across re-registrations (not removed during updates)
    • Each permission object in the array uses the same structured role format as endpoint permissions (see IAM Roles and Permissions Model)
  7. Registration Completion Response:

    • IAM sends a response message back to the module via the Platform API
    • See Registration Response Flow for complete details about response structure and usage
    • If a publicKey was provided in integration.config.values, the response will include the Keycloak client secret encrypted with that key — see Encrypted Client Secret Delivery

Deregistration (type: "deregistration"):

  1. Boundary Filtering: Same filtering logic as registration
  2. Client Lookup: Queries Keycloak for the client by clientId
  3. Complete Deletion:
    • Deletes the entire client from Keycloak if found
    • Removes all client configuration, service account, and assigned permissions
    • If client doesn't exist, logs informational message and continues

Client Permissions Behavior

Client permissions are assigned to the client's service account in the IAM module scope, enabling the client to call IAM API endpoints. This is distinct from endpoint permissions, which allow IAM to call your module's endpoints.

Key characteristics:

  • Scope: Always assigned in IAM module context (determined by IAM's ApplicationModuleName configuration)
  • Role Source: Must use role IDs from the IAM module's getRoles endpoint (not your module's roles). See IAM Module Roles for available IAM role types
  • Persistence: Permissions accumulate across re-registrations and are NOT removed during updates
  • Deletion: Only removed when client is deregistered (deleted entirely)
  • Optional: If permissions is null, an empty array, or omitted, no permissions are assigned

Example use case: A module's client needs IAM roles like { "action": ["view"], "resource": ["users"] } to query user information via IAM API endpoints.

Boundary Filtering

Boundaries control which IAM instances process the client registration (similar to endpoint boundary filtering):

  • Empty array: Treated as ["internal"]
  • Multiple boundaries: Client registered in all IAM instances with any matching boundary
  • No match: Registration silently skipped (logged at Information level)
  • Case-insensitive: Boundary comparison is normalized and case-insensitive

This ensures clients are only created in the appropriate environments (e.g., internal-only clients won't be created in external IAM instances).

Best Practices

  1. Use generated clientId: Let the system create {applicationId}-module-client for consistency and predictability
  2. Match boundaries: Ensure client boundaries align with your endpoint boundary settings to avoid split configurations
  3. Specify all URLs: Provide complete URL configuration (rootUrl, baseUrl, adminUrl) even if some OAuth flows don't require them
  4. Include necessary permissions: Only request IAM permissions your module actually needs to reduce attack surface
  5. Test both flows: Verify both registration and deregistration work correctly in your deployment pipeline
  6. Handle idempotency: Your module should handle multiple registration messages gracefully since IAM updates existing clients

Alternative Client Creation Methods

If the automated Hub Integration Message approach doesn't meet your needs, you can use these alternative methods:

Via IAM API Endpoint

Module Client Creation (Preconfigured)

Make a direct API call to create a module client with standard configuration:

POST /Client/module/{moduleId}
Authorization: Bearer <admin-token>

This endpoint automatically creates a client with:

  • Client ID: {moduleId}-module-client
  • Service account enabled
  • Standard flow and direct access grants enabled
  • Standard Token Exchange enabled (implements RFC 8693)
  • Required default client scopes: groups and custom-permissions_token-exchange
  • Audience mapper for iam-consumers
  • Confidential client with client authentication

Example request:

curl -X POST "https://<iam-api-url>/Client/module/my-module" \
  -H "Authorization: Bearer <admin-token>"

Example response:

{
  "clientId": "my-module-module-client",
  "name": "my-module Module Client",
  "id": "abc123-uuid",
  "enabled": true,
  "publicClient": false,
  "serviceAccountsEnabled": true
}

After creation, retrieve the client secret:

GET /Client/{clientUuid}/secret
Authorization: Bearer <admin-token>

Generic Client Creation (No Preconfiguration)

Alternatively, you can use the generic client creation endpoint for full control over the configuration:

POST /Client
Authorization: Bearer <admin-token>
Content-Type: application/json

{
  "clientId": "my-custom-client",
  "name": "My Custom Client",
  "enabled": true,
  "clientAuthenticatorType": "client-secret",
  "redirectUris": ["https://example.com/callback"],
  "webOrigins": ["https://example.com"],
  "serviceAccountsEnabled": true,
  "standardFlowEnabled": true,
  "directAccessGrantsEnabled": true
}

This generic endpoint creates a client without any preconfiguration, giving you complete control over all client settings. You'll need to manually configure:

  • Client scopes (including groups and custom-permissions_token-exchange)
  • Audience mappers
  • Token exchange settings
  • Any other required configuration

Use this approach when: You need a client configuration that differs from the standard module client setup.

Manual Client Creation in Keycloak

If you need custom configuration, you can create a client manually in Keycloak:

  1. Go to Clients and create a client:

    • Provide clientId
    • Turn on Client Authentication, Standard Flow, Direct access grants, Service account roles
    • Set login settings according to your module's needs
  2. Enable Standard Token Exchange:

    • In the Advanced settings tab, enable "OAuth 2.0 Token Exchange Enabled" (also known as Standard Token Exchange)
  3. Configure client scopes:

    • Add groups as a default client scope (not optional)
    • Add custom-permissions_token-exchange as a default client scope to include custom_permissions in token exchange
  4. Add recognized audience:

    • In client scopes, click on the "dedicated" scope for the client
    • Add mapper by configuration
    • Select Audience mapper type
    • Add iam-consumers to Included Custom Audience field
    • Check add to ID token and access token
  5. Add client audience to IAM API service account:

    • Navigate to the IAM API service account client in Keycloak
    • Go to Client scopes tab
    • Click on the "dedicated" scope for that client
    • Add mapper by configuration
    • Select Audience mapper type
    • Add your newly created client's clientId to Included Client Audience field
    • Check add to ID token and access token

    Critical for Token Exchange

    This step is required for token exchange to work. When IAM makes requests to your module endpoints (e.g., getRoles, getEntities, getEntityGroups), it sends its client token in the Authorization header. Your module must exchange this token to verify permissions. Token exchange will fail unless your client's clientId is included as an audience in the IAM client's token.

    In other words: If you create a client that will be used to exchange tokens initially requested by IAM's client, your clientId must be added as an audience to IAM's client. Otherwise, you won't be able to exchange the token.

    Note: This step is automatically performed when using the automated client creation methods (Hub Integration Message or API endpoint).

To use this client you need its clientId and clientSecret (Credentials tab).

Using the Client

After creating a client using any of the methods above (Hub Integration Message, API endpoint, or manual creation), you can use it to generate tokens.

Generate tokens by requesting them from Keycloak:

http://<keycloak-url or keycloak-service for cluster internal communication>/realms/<realm-name>/protocol/openid-connect/token

Token Exchange Required

Tokens used in Authorization headers for HTTP requests MUST NOT include custom permissions. Only exchange tokens when you need to check permissions. See Token Usage and Exchange Requirements for complete details.

POST http://<keycloak-url or keycloak-service for cluster internal communication>/realms/<realm-name>/protocol/openid-connect/token
Content-Type: application/x-www-form-urlencoded

grant_type=urn:ietf:params:oauth:grant-type:token-exchange
&client_id={{clientId}}
&client_secret={{clientSecret}}
&subject_token={{access_token}}
&subject_token_type=urn:ietf:params:oauth:token-type:access_token
&requested_token_type=urn:ietf:params:oauth:token-type:access_token
&scope=custom-permissions_token-exchange

Critical workflow:

  1. Generate initial token without custom-permissions_token-exchange scope for HTTP requests
  2. When you receive a request, exchange the incoming token to get custom permissions
  3. Use exchanged token only for authorization decisions, never in Authorization headers
  4. When making outgoing HTTP requests, use tokens without custom permissions

Connecting to IAM API:

To connect to the IAM API, tokens generated for your client must have:

  • audience: iam-consumers
  • Generated using the same Keycloak instance as IAM

Token Exchange Requirements:

Audience Configuration for Token Exchange

To exchange tokens generated by IAM's client (e.g., tokens received in the Authorization header of getRoles, getEntities, or getEntityGroups requests), your client's clientId must be added to IAM's client audiences first. This is configured in step 5 of Manual Client Creation. Without this configuration, token exchange will fail with an audience validation error.

See Token Usage and Exchange Requirements for complete implementation details.

Managing Client Permissions

After creating a client, you can manage its permissions using the IAM API. These are client permissions that allow the client to call IAM APIs.

You can add permissions to a client's service account using the IAM API:

POST /Client/{clientUuid}/permissions
Authorization: Bearer <admin-token>
Content-Type: application/json

{
  "module": "target-module",
  "roles": {
    "access": ["reader", "writer"]
  },
  "context": {
    "entities": ["E1"],
    "entityGroups": []
  }
}

Example:

curl -X POST "https://<iam-api-url>/Client/abc123-uuid/permissions" \
  -H "Authorization: Bearer <admin-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "module": "mock-module",
    "roles": {
      "access": ["reader"]
    },
    "context": {
      "entities": ["E1"]
    }
  }'

To retrieve all permissions assigned to a client:

GET /Client/{clientUuid}/permissions
Authorization: Bearer <admin-token>

To remove a permission from a client:

DELETE /Client/{clientUuid}/permissions/{permissionId}
Authorization: Bearer <admin-token>

Note: You need permissions to manage both the client and the target module's permissions to assign permissions to a client.

Additional Integration Topics

Sending Requests Directly to IAM API

When in the cluster, modules should communicate with IAM API using internal cluster communication (sending requests directly to the service for iam-backend). This way the requests skip OAuth authentication flow, which is primarily for user sessions, and skip unnecessary certificate validation keeping the traffic internal.

Important: When calling IAM API, use tokens without custom permissions in the Authorization header. The IAM API will perform token exchange internally when needed.

For development purposes during the integration process, it may be helpful to create an additional ingress pointing directly to iam-backend service to reproduce internal cluster communication. Otherwise, trying to send requests to the main hostname of IAM will result in authentication problems - the traffic for application's hostname goes through auth-gateway that will reject any requests that do not use tokens generated using the auth-gateway login flow.

When sending requests to Keycloak (token generation), use Keycloak service for cluster internal communication and for development purposes Keycloak hostname can be used though it may be necessary to ignore SSL validation.

Keycloak Configuration via keycloak-config-cli

You may need to configure additional Keycloak resources declaratively using the keycloak-config-cli tool. This allows you to customize clients, roles, users, identity providers, and other Keycloak settings through configuration files rather than manual UI changes.

Configuration Documentation

For complete documentation on declarative Keycloak configuration using values.yaml:

Configuration Options:

The IAM module provides two complementary methods for extending Keycloak configuration:

  • extraInlineConfig - Inject additional resources (clients, roles, groups, users) into existing configuration files. Best for simple, static additions.
  • extraConfiguration - Add entirely new configuration files with full Helm templating support. Best for complex configurations, identity providers, and environment-specific settings.

Common Use Cases:

  • Adding module-specific OAuth clients with custom redirect URIs
  • Creating development users and roles
  • Configuring external identity providers (OIDC, SAML)
  • Setting up authentication flows and client scopes
  • Defining realm-level settings and policies

Both methods are documented with complete examples, comparison tables, and troubleshooting guidance in the Configuration Guide.