How to Configure Keycloak to Validate Resource and Scope Access During Client Credential Flow?

Hi everyone,

I’m working on configuring Keycloak for the following use case:

I have a resource server with two resources (r1 and r2):

  • r1 has two scopes: s1 and s2.
  • r2 has three scopes: s3, s4, and s5.

There are two clients (c1 and c2). Access to resource/scope combinations is determined by business logic. For example:

  • A specific subscription might be required to grant s2 for r1.
  • Another subscription might be required for s5 of r2.

End Requirement:

  • When clients request access tokens using the Client Credentials Flow in OAuth2, they specify the scopes they need.
  • Keycloak must validate the requested scopes against what the client is allowed to access.
  • If a requested scope isn’t allowed, it should not be included in the issued access token.

For example:
If c1 requests r1:s1 and r2:s3, but it’s only allowed r1:s1, Keycloak should issue an access token containing only r1:s1.

Approach So Far:
One way I found to implement this is by using Client Scopes:

  1. For each allowed resource/scope combination, create a client scope (e.g., r1:s1).
  2. Assign the relevant client scopes to the client (e.g., assign r1:s1 to c1).
  3. This way, when c1 requests r1:s1, Keycloak includes it in the token. But if c1 requests r1:s2, it’s denied because it doesn’t have the associated client scope.

This approach seems to work without requiring the Resource Server, Policies, or Permissions setup in the Authorization tab.

My Questions:

  1. Is this the correct way to implement this use case in Keycloak?
  2. Are there better or more flexible alternatives using Resource Server, Policies, and Permissions?
  3. What are the potential downsides of using only Client Scopes in this way?

Thank you for your guidance!