Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Administer Keycloak: realms, users, roles

27 min read
Improve this page

Logo Keycloak

This guide teaches you to administer Keycloak through the web console. After the Docker installation (in French), you will create a realm, manage users in groups, assign roles and configure a client. These gestures are the foundation of any Keycloak operation.

What you will learn

By the end of this lesson, you will be able to:

  • Navigate the admin console efficiently
  • Create and configure realms
  • Manage users and their credentials
  • Organize users into hierarchical groups
  • Create and assign roles (realm and client)
  • Configure a basic client
  • Monitor active sessions and events

Access the admin console

Open http://localhost:8080: Keycloak redirects you to the console login screen (/admin/master/console/).

Sign in with the credentials created during the installation:

  • Username: admin
  • Password: the one set in KC_BOOTSTRAP_ADMIN_PASSWORD

The area that matters most in this table is the realm selector. All the other sections show the content of the active realm without naming it: creating a user while believing you are working on lab, when the selector still shows master, is a classic mistake of the first days. Get into the habit of checking the name displayed at the top left before creating any object.

AreaDescription
Realm selector (top left)Switches between the available realms
Side menuAccess to the different sections (Clients, Users, Groups, etc.)
Main areaConfiguration forms and lists
BreadcrumbHierarchical navigation within the configuration

Understand realms

A realm is an isolated space for identity management. Each realm has its own:

  • Users and groups
  • Roles and permissions
  • Clients (applications)
  • Login settings
  • Tokens and sessions

The master realm vs application realms

The master realm is created at first startup and holds the instance administration account. An account in this realm can administer all the other realms: adding your end users to it amounts to giving them a foothold in the admin console. The separation below is therefore not a naming convention, it is a privilege boundary.

RealmUsageUsers
masterAdministration of Keycloak itselfSuper-admins only
Application realmsApplications and end usersThe users of your apps

Create an application realm

The realm name appears in all of Keycloak's public URLs (/realms/<name>/...) and your applications will carry it in their configuration. Renaming it afterwards breaks every client already configured, so choose it at creation time, in lowercase and without spaces.

  1. Sign in to the admin console
  2. Click the realm selector (top left, shows "master")
  3. Click Create realm
  4. Fill in the information:
    • Realm name: lab (lowercase, no spaces)
    • Enabled: On
  5. Click Create

You are automatically switched to the new realm.

Configure a realm

The four tabs below match the actual tabs of the Realm settings screen. The two that change what your users see are Login (what the login page offers) and Sessions (how long before they are signed out). The values shown are those of a training realm, mostly the Keycloak defaults: in production, Verify email goes to On (with an SMTP server configured) and you reconsider the session durations according to your risk level.

SettingRecommended valueDescription
Display nameLab TrainingName shown to users
HTML Display name<b>Lab</b> TrainingWith HTML for branding
Frontend URL(empty in dev)Public URL in production

There is no "Refresh Token Lifespan" setting at the realm level: the validity of a refresh token is bounded by the session, therefore by SSO Session Idle (inactivity) and SSO Session Max (absolute duration), in the Sessions tab. The Access Token Lifespan is set in the Tokens tab.

Manage users

Users are identities that can sign in to your applications.

Create a user

The only truly required field is Username, and it is unique within the realm: two realms can host an alice without conflict. The account created here has neither a password nor a role, so it cannot sign in yet. This is normal, the next two sections (credentials, then roles) fill in these two gaps.

  1. In the menu, click Users
  2. Click Add user
  3. Fill in the information:
    • Username: alice (required, unique within the realm)
    • Email: alice@example.com
    • First name: Alice
    • Last name: Martin
    • Enabled: On
  4. Click Create

Configure credentials

A newly created user does not have a password yet. The deciding switch on this screen is Temporary: left On, Keycloak automatically adds the UPDATE_PASSWORD required action to the account, and the user will have to choose their own password at first login. This is the setting to keep whenever an administrator types the password for someone else, otherwise you know your user's secret.

  1. After creation, go to the Credentials tab
  2. Click Set password
  3. Enter the password twice
  4. Temporary:
    • On = the user will have to change it at first login
    • Off = permanent password
  5. Click Save

User attributes

Attributes let you store metadata about the user, in the Attributes tab, as key/value pairs. Keep in mind that an attribute added here does not leave Keycloak on its own: it stays in the database until a client mapper has explicitly copied it into the token. The examples below are common ones: applications use them to make an authorization decision or fill in a profile.

AttributeExampleUsage
departmentEngineeringCompany department
employee_idEMP-001HR identifier
phone+33612345678Phone number

These attributes can be included in tokens through mappers (see Protocol mappers and claims).

Required actions

Required actions force the user to do something at the next login. They are set on a specific account from the Details tab, Required User Actions section, and Keycloak interrupts the login flow until the action is done. This is the lever to use to enforce MFA on a handful of sensitive accounts without enabling it for the whole realm, or to force a password update after an incident.

ActionDescription
UPDATE_PASSWORDChange the password
VERIFY_EMAILVerify the email address
UPDATE_PROFILEComplete the profile
CONFIGURE_TOTPSet up MFA (TOTP)

VERIFY_EMAIL requires an SMTP server to be configured in Realm settings > Email: without it, the user ends up stuck on a screen waiting for an email that will never be sent.

Organize with groups

Groups let you organize users and assign them attributes and roles collectively.

Group hierarchy

Groups can be nested. A user in a subgroup inherits the attributes and roles of the parent group, and inheritance always flows in that direction: belonging to Employees/Engineering/Backend also gives what Employees carries, never the reverse. The tree below shows what this looks like for a typical organization.

Employees/
├── Engineering/
│ ├── Backend/
│ └── Frontend/
├── Marketing/
└── Sales/

So put the broadest rights at the top (Employees) and add to the leaves only what is truly specific. A right set too high spreads to the whole company without anyone noticing.

Create a group hierarchy

A subgroup is not created from the root screen: you must first open the parent group, then click Create group again from inside it. This is the only subtlety of this procedure, and the one that leaves you with Engineering next to Employees instead of inside it.

  1. In the menu, click Groups
  2. Click Create group
  3. Name: Employees, then Create
  4. Click the Employees group to open it
  5. Click Create group from inside the group (this creates a subgroup)
  6. Name: Engineering, then Create
  7. Repeat for Marketing and Sales

Assign a user to a group

Membership is set from the user's page, not from the group. Always select the full path (Employees/Engineering) and not the short name: two subgroups with the same name under different parents are perfectly legal in Keycloak, and the list shows both.

  1. Go to Users and select a user
  2. Click the Groups tab
  3. Click Join group
  4. Select the group (e.g. Employees/Engineering)
  5. Click Join

After Join, the Groups tab shows the direct membership. Inherited groups only appear if you uncheck the Direct membership option: this is the way to check what the user actually receives from the hierarchy.

Group attributes

An attribute set on a group is inherited by all its members, present and future. This is what lets you stop entering department account by account: the day someone changes teams, changing their group updates all their metadata at once. As with user attributes, the value only reaches the token if a mapper is configured on the client.

  1. Go to Groups and select a group
  2. Click the Attributes tab
  3. Add an attribute: department = Engineering
  4. Click Save

All members of the group will have this attribute available in their tokens (if a mapper is configured).

Create and assign roles

Roles define users' permissions in applications.

Role types

The distinction that matters in this table is scope. A realm role describes who the person is in the organization (staff, manager), a client role describes what they are allowed to do in a specific application (app:read). The composite role is not a third type: it is a realm role or a client role to which other roles have been attached.

TypeScopeExampleUsage
Realm rolesGlobal to the realmadmin, userCross-cutting permissions
Client rolesSpecific to a clientapp:read, app:writeApplication permissions
Composite rolesCombine other rolesmanager = user + app:readPermission bundles

This separation avoids a classic trap: naming a realm role billing-admin when it only concerns a single application. The day a second application arrives, nobody knows what the role gives access to anymore.

Create a realm role

A role name is effectively immutable: it ends up in tokens and in the code of the applications that test for it. Stick to lowercase without spaces, and fill in the Description, the only place where you can explain in six months why this role exists.

  1. In the menu, click Realm roles
  2. Click Create role
  3. Role name: staff (lowercase, no spaces)
  4. Description: Company employee
  5. Click Save

Also create the manager and admin roles.

Create a composite role

A composite role groups several roles so that only one needs to be assigned. There is no "Composite" switch to turn on in the console: a role becomes composite when you attach a first associated role to it, and the Composite column of the role list then switches to True. Removing all associated roles turns it back into a simple role.

  1. Open the role to transform in Realm roles (e.g. manager)
  2. In the Action menu at the top right, choose Add associated roles
  3. Filter on realm roles or on a client's roles depending on what you want to include
  4. Check the roles to include (e.g. staff)
  5. Click Assign

A user with the manager role will automatically have the staff role. Nesting is recursive: admin as a composite of manager, itself a composite of staff, does give all three roles in the token. Limit yourself to two or three levels, beyond that nobody can work out an account's effective rights anymore.

Assign a role to a user

This procedure creates a direct link between a person and a role. It is justified for a special case (a replacement, a technical account), but it is not visible from the group: reserve it for exceptions and go through groups for everything else.

  1. Go to Users and select a user
  2. Click the Role mapping tab
  3. Click Assign role
  4. Select the role (e.g. staff)
  5. Click Assign

Assign a role to a group

This is the way of working to favor. The role is set only once, and a person's arrival or departure is handled by having them join or leave the group, without ever touching the roles again. A role set on a parent group also flows down into all its subgroups.

  1. Go to Groups and select a group
  2. Click the Role mapping tab
  3. Click Assign role
  4. Select the role (e.g. staff)
  5. Click Assign

All members of the group automatically inherit the role. To check what an account really receives, go back to its page, Role mapping tab, and uncheck Hide inherited roles: the list then shows the direct roles, those coming from groups and those coming from composites.

Default roles

Default roles are automatically assigned to every new user, including those created by LDAP federation or by self-service registration. Keycloak creates one by default per realm, named default-roles-<realm>: it is a composite that already carries the account client roles giving access to the Account Console. Add your roles to it rather than creating a second one.

  1. Go to Realm settings > User registration
  2. In Default roles, click Assign role
  3. Select the role or roles to add (e.g. staff)

Configure clients

A client represents an application that authenticates with Keycloak.

Client types

The selection criterion is simple: can your application keep a secret? The code of a single-page web application or a mobile application is downloaded to the user's device, so it is readable: it must be public. A backend running on your servers can hold a secret, so it will be confidential.

A public client makes up for the lack of a secret with PKCE, a proof generated at each login that makes an intercepted authorization code unusable. To enable it, open the client's Settings tab, Capability config section, and turn on the Require PKCE switch. The lesson on securing an application details the procedure.

TypeClient authentication settingUsage
PublicOffSPAs, mobile applications (no secret)
ConfidentialOnBackend, API (with a client secret)

Create a basic client

Two settings in this wizard deserve your attention. Standard flow enables the Authorization Code Flow, the one that redirects the user to the Keycloak login page: it is the only recommended flow for a web application. Direct access grants, by contrast, lets the application collect the password itself in order to exchange it for a token, which defeats the point of SSO and is discouraged by RFC 9700 (OAuth 2.0 security best current practice): keep it Off.

  1. In the menu, click Clients
  2. Click Create client
  3. Fill in General settings, then click Next:
    • Client type: OpenID Connect
    • Client ID: my-app
  4. Fill in Capability config, then click Next:
    • Client authentication: Off (public client)
    • Authorization: Off
    • Standard flow: On
    • Direct access grants: Off (recommended)
  5. Fill in Login settings, then click Save:
    • Root URL: http://localhost:3000
    • Valid redirect URIs: http://localhost:3000/callback
    • Web origins: http://localhost:3000

Client roles

A client role lives inside the client: it does not appear in the Realm roles list and two clients can each have an admin role without stepping on each other. This lets you name permissions from the application's point of view (app:admin, invoice:approve) without polluting the realm's global namespace.

  1. Select your client in Clients
  2. Go to the client's Roles tab
  3. Click Create role
  4. Role name: app:admin
  5. Click Save

These roles appear in tokens if the user has them.

Monitor sessions

The Sessions section lets you see who is signed in and invalidate sessions.

View active sessions

This screen is your first source of information during an incident: it answers "who is signed in right now, and from which address". The Last access column is the one to watch, because it is the one Keycloak compares with the SSO Session Idle configured above to decide when to expire the session.

  1. In the menu, click Sessions
  2. You see the list of active sessions with:
    • User
    • IP
    • Session start
    • Last access

Invalidate a session

Deleting a session ends SSO on the Keycloak side, but access tokens already issued remain valid until they expire. This is exactly why the recommended lifetime of an access token is short: it bounds the delay during which a forced sign-out has not yet taken effect on APIs.

  1. In Sessions, find the session
  2. Click the trash icon
  3. Confirm the sign-out

Invalidate all of a user's sessions

This is the procedure to follow for a compromised account, and it goes hand in hand with changing the password (or disabling the account): signing out without changing the password lets the attacker sign back in immediately and obtain a new refresh token, changing the password without signing out leaves already open sessions alive. A user signed in from several browsers has several sessions, hence the Sign out all sessions button.

  1. Go to Users and select the user
  2. Click the Sessions tab
  3. Click Sign out or Sign out all sessions

Configure events

Events let you audit actions in Keycloak.

Event types

Keycloak separates two logs that do not answer the same questions. Login events tell you what end users did (sign in, fail, sign out), admin events tell you what administrators changed in the configuration. Both are enabled separately and are disabled by default: until you have turned them on, there is nothing to consult, even retroactively.

TypeExamplesUsage
Login eventsLOGIN, LOGIN_ERROR, LOGOUTAudit of authentications
Admin eventsCREATE_USER, UPDATE_ROLEAudit of admin actions

Enable events

Two settings have a cost that you should measure before pushing them to production. Expiration defines how long Keycloak keeps the rows in its database: with no value, the table grows indefinitely. Include representation stores the full JSON payload of each change, which is valuable for an investigation but multiplies the volume, and can bring personal data into the audit database.

  1. Go to Realm settings > Events
  2. User events settings tab:
    • Save user events: On
    • Expiration: 30 days
    • Event types: check the events to capture
  3. Admin events settings tab:
    • Save admin events: On
    • Include representation: On (stores the payload)
  4. Click Save

View events

The event type to know first is LOGIN_ERROR: each row carries an error field (invalid_user_credentials, user_disabled, invalid_client_credentials) that gives the exact cause of the refusal, where the user only sees a generic message. This is the first place to look when someone says "it doesn't work".

  1. In the menu, click Events
  2. Use the filters:
    • User events: by type, user, date
    • Admin events: by operation, resource
  3. Click an event to see the details

Account Console

The Account Console is the end-user interface for managing their own account.

Access it at: http://localhost:8080/realms/lab/account/

Users can:

  • View and edit their profile
  • Change their password
  • Manage their active sessions
  • Set up MFA
  • See the authorized applications

Wrap-up exercise: administer a complete realm

Put the concepts into practice with this guided exercise.

Goal

Create a complete realm with users organized into groups and roles.

Lab steps

Follow these seven steps in order: each one builds on the previous. The sequence reproduces that of a real setup, where you first build the structure (realm, groups, roles) before placing people in it. The last step is the one that counts: it is the only one that checks that the whole thing works from a user's point of view.

  1. Create the realm:

    • Name: lab
    • Check the sessions: SSO Idle = 30 min, Access Token = 5 min (default values)
  2. Create the group hierarchy:

    Employees/
    ├── Engineering/
    └── Marketing/
  3. Create the roles and assign them to the groups:

    • Realm roles: staff, manager, admin
    • manager is composite and includes staff
    • admin is composite and includes manager
    • Employees → role staff
    • Employees/Engineering → no additional role (inherits staff)
  4. Create the users, each in their own group and with their direct role:

    UserEmailGroupDirect role
    alicealice@example.comEngineering(inherits staff)
    bobbob@example.comEngineeringmanager
    charliecharlie@example.comMarketing(inherits staff)
  5. Create a test client:

    • Client ID: test-app
    • Type: Public (OIDC)
    • Redirect URIs: http://localhost:3000/callback
  6. Enable events:

    • Login events: On
    • Admin events: On
  7. Validate:

    • Sign in to the Account Console as alice
    • Check the login events in the admin console

Success criteria

Tick this list in the console, not from memory. The most telling point is the last one: if the login events do not appear even though the sign-in succeeded, Save user events was turned on after the test, and events that have already happened are never caught up.

  • Realm lab created, session durations checked
  • Hierarchical groups created (Employees/Engineering, Employees/Marketing)
  • Roles staff, manager (composite), admin (composite) created
  • Role staff assigned to the Employees group
  • Users created in the right groups
  • Client test-app configured
  • Login events visible after a user signs in

Troubleshooting

The user cannot sign in

Go through these three checks in this order: they run from the most visible to the most precise. The third is the only one that gives the actual cause, the first two rule out the common explanations in a few seconds.

  1. Check that the account is Enabled in the admin console
  2. Check that credentials are set (Credentials tab)
  3. Check the events of type LOGIN_ERROR to read the error message

If the account shows a pending required action, the sign-in succeeds but the user stays stuck on an intermediate screen, which is often described as "I can't sign in".

Roles do not appear in the token

A role missing from the token does not mean it is not assigned: between the assignment and the token, there are the role mapping and then the client scope. First decode the token with an offline tool to find out whether the role is missing from realm_access.roles or from resource_access, which will tell you which of the three steps below failed.

  1. Check that the role is indeed assigned (direct or through a group)
  2. Check the client's mappers (see Protocol mappers and claims)
  3. For client roles, check that the scope is included

The Account Console shows "Page not found"

Check the URL: http://localhost:8080/realms/{realm-name}/account/

Replace {realm-name} with the exact name of your realm (e.g. lab).

Key takeaways

ConceptKey point
RealmIsolated space of identities, one per environment/application
MasterReserved for super-admins, never for applications
GroupsOrganize users with inheritance of attributes and roles
Realm rolesPermissions global to the realm
Client rolesPermissions specific to an application
Composite rolesGroup several roles to simplify administration
SessionsMonitor and invalidate active connections
EventsDisabled by default: enable them to audit sign-ins and administration actions