Restrict access to OIDC identity provider (CSAM) logins to internal employees only

Hello KC community,

I have set up a KC server (v26) with a user federation (Active Directory) and an external OIDC identity provider (Belgian federal authentication service - CSAM).
So, a client application using the KC server to authenticate its users offers two authentication methods.

The first method, using a username and password from our Active Directory, can only be used by employees. The second method, via CSAM, can be used by any citizen or person working in Belgium.

In the KC user model, a field called “nrn” has been added. It is populated with the unique identifier assigned by the state to every citizen. This field is mapped both to a field in our AD users and to an attribute returned by CSAM.

That’s the context.

The issue is the following:
I have a client application where only employees should be allowed to log in. However, I want them to be able to use CSAM to do so.
However, since CSAM allows any citizen to log in, I need a way for Keycloak to verify — when CSAM is used as the identity provider — whether the authenticated user is actually an employee (i.e., present in our AD), and to make this information available to the client application (e.g., via a claim).

I don’t see how I can do that.

Additional note: there is no filtering possible on the client application side.

Since you plan to allow login from both IDPs, I assume Keycloak is able to link the accounts via username. If so, you could require that users log in via AD the first time to ensure they are in fact employees: Set CSAM setting “Account Linking Only” to ensure that they can log in via CSAM, but only after verifying their employee status via AD on their first login. Issue here is that their employee status can change (e.g. no longer employed) which isnt verified explicitly on every login in this case.

Alternatively, build a custom claim mapper used with CSAM to look up the user in your AD and determine their status and any essential AD attributes that you’d like to map to user attributes (and later to claims via client scopes).

Usually, you delegate the authorization part to the application, since all the necessary information is available in the identity tokens.
I don’t like when Keycloak acts as the Policy Enforcement Point (PEP), but if you can’t handle authorization at the application level (which I recommend - the app should act as the PEP based on the identity token claims), you can review the following SPI that helps restrict user authorization on clients or use it as inspiration based on your use case.