Keycloak: Role based client log-in access restriction for users

The solution proposed by @Stuck is a great start, but it has a significant flaw: When the user has already authenticated, e.g. via the standard flow of another client that did not require the role, the password form flow will never be triggered. Consequently, the user will be logged in via the cookie flow without ever checking for the role.

In other words: If there are other clients (such as the account console) that do not require the role, anyone can bypass the role check.

To fix this there needs to be an additional flow layer that includes all authentication executions, that is followed by the authorization step (no matter what authentication flow was used). The final result will look like this:

enter image description here


You can do this without extensions.

  • Copy the desired flow (e.g. the browser flow)
  • Create a new sub flow (e.g. for the browser forms) and call it Access By Role and select generic as type.
  • For the new sub flow ensure that CONDITIONAL is selected in the flow overview.
  • For the new sub flow add execution Condition - User Role, make it REQUIRED and configure it:
    • alias: admin-role-missing
    • role: admin (or whatever your role is)
    • negate: true
  • Add another execution: Deny Access and make it REQUIRED as well.

The final result should look similar to this: enter image description here

This will deny access if the condition "admin-role-missing" is true.

You an also learn more from the docs: explicitly-deny-allow-access-in-conditional-flows

Also, don't forget to go to your client and select the flow in the authentication overrides.