What Is a Service Account in Keycloak?

What Is a Service Account in Keycloak?

A complete, beginner-to-intermediate guide to Keycloak service accounts — what they are, why they exist, how they work internally, and how to use them safely in real systems.

Imagine an office building where every person who enters has to show an ID badge at the front desk. Employees badge in with their own card, and everyone understands that. But what about the automated mail-sorting robot that also needs to move between floors to deliver packages? It isn’t a person — it doesn’t have a face, a desk, or a lunch break — yet it still needs to prove who it is before the elevator will let it through. In the world of identity and access management, that robot is a “machine,” and the badge it wears is called a service account. Keycloak, the open-source identity and access management platform, gives every application a way to get that badge automatically. This tutorial walks through exactly what that badge is, how Keycloak issues it, how it is used, and how to keep it from being stolen.

1What Is Keycloak, in One Minute

Before service accounts make sense, you need a quick picture of the system they live inside.

Keycloak is an open-source Identity and Access Management (IAM) server. Its job is to answer two questions for every request that hits your applications: “Who are you?” (authentication) and “What are you allowed to do?” (authorization). Instead of every application writing its own login page, password database, and permission logic, they all delegate that work to Keycloak. Keycloak issues digital tokens — small, cryptographically signed pieces of text — that prove identity and carry permissions, and applications simply trust those tokens.

Simple Analogy

Think of Keycloak as the security desk of a large office complex with many buildings (your applications). Instead of each building having its own separate guard who checks IDs differently, there is one central security company that issues one universal badge. Every building’s door reader trusts that badge because it was issued by the same trusted security company.

Keycloak organizes everything inside a realm — an isolated space containing its own users, applications (“clients”), roles, and policies. Within a realm, you register each application as a client. A client can be a web app, a mobile app, an API, or — importantly for this tutorial — a backend service that has no human user directly attached to it.

Term

Realm

An isolated tenant in Keycloak containing its own users, clients, and configuration.

Term

Client

Any application or service registered in Keycloak that wants to use authentication.

Term

Token

A signed, time-limited piece of data proving identity and/or permissions.

Term

Role

A named permission (e.g. “order-reader”) that can be granted to a user or a client.

2Core Concept — What a Service Account Actually Is

A service account in Keycloak is a special, automatically generated user that represents an application instead of a human being. When you register a confidential client in Keycloak and enable the “service accounts” option on it, Keycloak silently creates a hidden user behind the scenes, usually named something like service-account-<client-id>. This hidden user has no password, never logs in through a browser, and never sees a login screen. Instead, the client itself authenticates using its own client credentials (a client ID and a client secret, or a certificate), and Keycloak treats that authentication as if this invisible user had logged in.

i
Key Insight

A service account is not a separate feature bolted onto Keycloak — it is simply a user object that is permanently linked, one-to-one, to a specific client. Whatever roles you assign to that user, the client effectively “becomes” when it authenticates.

Why does this matter? Because most authorization systems, including Keycloak, are built around the idea of a “subject” that holds roles and permissions. Humans are subjects. But machines — batch jobs, microservices, cron scripts, CI/CD pipelines, IoT devices — also need to be subjects sometimes. Rather than inventing a completely separate permission system just for machines, Keycloak reuses its existing user-and-role model and simply gives each machine client a dedicated, machine-only “user” to hang roles on.

Simple Analogy

Picture a company where every employee has an ID badge with a name and a list of door-access permissions. Now imagine the company also has a delivery robot. Instead of building a whole new access-control system just for robots, the facilities team simply creates a badge for the robot too — “Robot #7” — and gives that badge the exact doors it is allowed to open. The robot never has a face or a home address, but the badge system doesn’t care; it just checks the badge.

Practically speaking, this means a service account can do almost everything a normal user can do inside the authorization model: it can be assigned realm roles, client roles, and group memberships (in newer Keycloak versions), and those roles will appear inside the access token the client receives. The one thing it typically cannot do is interactively log in through the standard browser-based login form, because it has no password and no human behind it.

3Why Service Accounts Exist

Every design decision in software exists to solve a real problem. Here is the problem service accounts solve.

Modern systems are rarely a single application. A typical setup includes a frontend, several backend microservices, a message queue, a batch-processing job, a reporting tool, and a CI/CD pipeline that deploys new versions automatically. Many of these components need to call each other’s APIs — with no human sitting at a keyboard to type a username and password. If you don’t have a proper mechanism for this, teams tend to fall into two bad habits:

Without Service Accounts (Anti-pattern)

  • Hardcoding a real human’s username and password into a script
  • Sharing one “admin” account across ten different automated jobs
  • Disabling authentication entirely between internal services (“trust the network”)
  • Creating fake “robot” human users with real passwords that never expire

With Service Accounts (Correct Pattern)

  • Each service gets its own identity, tied to a client, not a person
  • Credentials are a client secret or certificate, not a human password
  • Permissions are scoped narrowly per service (least privilege)
  • Access can be revoked instantly by disabling one client

Service accounts exist specifically to close this gap. They let machine-to-machine (M2M) communication use the exact same trusted identity infrastructure that human logins use — the same token format, the same signing keys, the same audit trail, the same role model — without ever needing a human’s credentials or an insecure shortcut.

Typical Trigger: Microservice-to-Microservice Calls

An “Order Service” needs to call an “Inventory Service” to check stock levels. Neither call originates from a logged-in customer. The Order Service authenticates as itself, using its own service account, and receives a token proving “I am the Order Service” that the Inventory Service can verify and authorize.

Typical Trigger: Scheduled Batch Jobs

A nightly job that archives old records needs to call an internal API at 2 AM when no one is awake. It uses its own service account to authenticate on a timer, with no human involvement at all.

Typical Trigger: CI/CD Pipelines

A deployment pipeline needs to call a management API to roll out a new container image. It authenticates using a service account scoped only to “deploy,” so a compromised pipeline can’t also delete customer data.

4Architecture and Components

Let’s look at the moving pieces that make a service account work.

A Keycloak service account is built from a small number of interlocking pieces. Understanding each one individually makes the whole picture click into place.

Component

Confidential Client

The client representing your application must be marked “confidential” (not public), meaning it can safely hold a secret because it runs on a trusted server, not in a browser.

Component

Client Secret / Certificate

A shared secret string (or a mutual-TLS certificate) that only the real application and Keycloak know, used to prove the client’s identity.

Component

“Service Accounts Enabled” Flag

A toggle on the client’s settings that tells Keycloak to generate the hidden linked user automatically.

Component

The Service Account User

The auto-created, passwordless user object (named service-account-<client-id>) that actually holds the roles.

Component

Assigned Roles

Realm roles and/or client roles attached to the service account user, defining exactly what the application is allowed to do.

Component

Token Endpoint

Keycloak’s OAuth2 /token endpoint, which the client calls directly to exchange its credentials for an access token.

All of these pieces live inside a single realm. The client and its service-account user are two separate objects in Keycloak’s data model, but they are permanently bound together — you cannot delete one without affecting the other, and you generally manage the service account’s roles from a dedicated “Service Account Roles” tab right on the client’s own configuration page.

graph TD
    A[Confidential Client] -->|has service accounts enabled| B[Service Account User]
    B -->|assigned| C[Realm Roles]
    B -->|assigned| D[Client Roles]
    A -->|authenticates with| E[Client ID and Secret]
    E -->|sent to| F[Keycloak Token Endpoint]
    F -->|issues| G[Access Token]
    G -->|contains| C
    G -->|contains| D
    G -->|presented to| H[Protected API / Resource Server]
        
FIG 1 — How a client, its service account, and its roles connect to produce a usable access token

5Internal Working — How Keycloak Sets It Up

When an administrator flips the “Service Accounts Enabled” switch on a client and saves it, Keycloak performs a small but important sequence of internal steps. Understanding this sequence removes a lot of the mystery around why the feature behaves the way it does.

1

Client Validated as Confidential

Keycloak checks that the client’s access type allows it to hold a secret. Public clients (like single-page apps running fully in a browser) are not allowed to have service accounts, because they cannot safely store a secret.

2

A Dedicated User Is Created

Keycloak creates a new user record in the realm’s user store, typically named service-account-<client-id>. This user is flagged internally as a “service account user” and is linked to the client’s internal ID.

3

No Credentials Are Set on the User

Unlike a normal user, no password or credential is ever stored for this user — it can never be used to log in through a form, because only the client’s own secret unlocks it.

4

Default Roles Are Attached

The new user inherits the realm’s default roles (if any), just like a normal new user would, unless an administrator removes them.

5

Admin Assigns Application-Specific Roles

The administrator then visits the “Service Account Roles” tab on the client and grants exactly the realm roles and/or client roles this application needs — nothing more.

!
Common Misconception

People sometimes assume the service account is a “fake” object that behaves differently under the hood from a real user. It isn’t. To the rest of Keycloak’s authorization engine, it is a genuine user — it just happens to have no password and to be created and controlled automatically.

6Data Flow and Lifecycle — The Client Credentials Grant

This is the actual conversation that happens between an application and Keycloak, step by step.

Service accounts authenticate using an OAuth 2.0 flow called the Client Credentials Grant. It is deliberately the simplest of all OAuth2 flows, because there is no human involved to redirect to a login page, type a password, or click “Allow.” The application simply presents its own identity directly.

sequenceDiagram
    participant App as Backend Service (Client)
    participant KC as Keycloak Token Endpoint
    participant API as Protected Resource API

    App->>KC: POST /token grant_type=client_credentials, client_id, client_secret
    KC->>KC: Validate client_id and secret
    KC->>KC: Load service account user and its roles
    KC-->>App: Access Token (JWT with roles/claims)
    App->>API: Call API with Authorization: Bearer token
    API->>API: Verify token signature and roles
    API-->>App: Response (allowed or denied based on roles)
        
FIG 2 — The Client Credentials Grant used by service accounts

Notice what is absent from this diagram: there is no browser redirect, no login form, and no consent screen. The entire exchange happens in a single, direct, server-to-server HTTP call. This is precisely why service accounts are the right tool for machine-to-machine communication and the wrong tool for anything involving a human user — humans should always go through an interactive flow (like Authorization Code) so they can see and control what they’re logging into.

Simple Analogy

A human employee badges in at a turnstile by scanning their card and sometimes showing their face to a camera — an interactive check. A delivery robot, by contrast, simply broadcasts a short encrypted signal to the turnstile that says “I am Robot #7, here is my secret code,” and the turnstile opens instantly if the code matches. No screen, no interaction — just a direct, automated exchange.

The resulting access token is a signed JSON Web Token (JWT). Inside it, the “subject” claim identifies the service account user, and the roles/claims sections list every realm role and client role that was assigned to that service account. Downstream APIs never need to call back to Keycloak to check permissions for every request — they simply verify the token’s digital signature and read the roles straight out of it. This makes the whole system fast, because trust is established once, at token-issuance time, and then carried along inside the token itself for its short lifetime.

StageWho InitiatesWhat Happens
Token RequestThe client applicationSends client_id and client_secret to Keycloak’s token endpoint
ValidationKeycloakConfirms the secret matches, then loads the linked service account user
Token IssuanceKeycloakBuilds and signs a JWT containing the service account’s roles and claims
Token UsageThe client applicationAttaches the token as a Bearer credential on outgoing API calls
Token ExpiryAutomaticThe token becomes invalid after its lifespan; the client must request a new one

7Security Considerations

A service account is powerful precisely because it needs no human to operate it — which is exactly why it must be protected carefully.

Because a service account’s “password” is really just a shared secret string (or, in stronger setups, a certificate), that secret becomes the single point of trust for the entire identity. If it leaks — say, it’s accidentally committed to a public code repository — anyone who finds it can impersonate the application, with whatever roles that account holds, for as long as the secret remains valid.

!
Most Common Mistake

Assigning a service account broad roles “just in case,” such as a realm-admin or manage-users role, when the application only ever needs to read a handful of records. A leaked secret for an over-privileged service account can be catastrophic; a leaked secret for a narrowly scoped one is a much smaller incident.

Keycloak provides several tools that meaningfully reduce this risk when used correctly:

Control

Least-Privilege Roles

Grant only the exact realm/client roles the service genuinely needs, never broad administrative roles.

Control

Secret Rotation

Regenerate the client secret on a schedule, and immediately whenever a leak is suspected.

Control

Mutual TLS / Signed JWT Auth

Replace the plain shared secret with a client certificate or a signed JWT assertion for stronger proof of identity.

Control

Short Token Lifetimes

Keep access tokens short-lived so a stolen token becomes useless quickly, even if the secret itself is fine.

Control

Secret Storage in a Vault

Store the client secret in a dedicated secrets manager rather than in configuration files or source code.

Control

Audit Logging

Log every token issuance event for service accounts so unusual activity can be detected and investigated.

“A service account’s secret is not a password you memorize — it is a key you must actively protect.”

It’s also worth understanding what a service account cannot do by default. It cannot perform interactive login, meaning phishing attacks that target humans (fake login pages, for example) simply do not apply to it. Its entire attack surface is the secret itself and the roles attached to it — which is exactly why hardening those two things covers the overwhelming majority of real-world risk.

8Design Patterns and Anti-Patterns

Over years of production use, a handful of clear patterns have emerged for how teams successfully use Keycloak service accounts — and a matching set of anti-patterns that consistently cause pain later.

ANTI-PATTERN-01 Avoid
Problem

One shared service account is reused across five unrelated microservices to “save time” during setup.

Why It’s Harmful

Every one of those five services now shares the exact same permissions and the exact same secret. If any single service is compromised, all five are effectively compromised. It also becomes impossible to tell, from the audit logs, which specific service actually made a given call.

Correct Approach

Create one client — and therefore one service account — per logical service, each scoped to only the roles that specific service needs.

ANTI-PATTERN-02 Avoid
Problem

A developer creates a normal human user account with a real password, names it “robot-user,” and uses it inside an automated script instead of using a proper service account.

Why It’s Harmful

Human user accounts are designed for interactive login and password policies (expiry, resets, multi-factor prompts) that break automated scripts unpredictably, and they blur the audit trail between “a person did this” and “a machine did this.”

Correct Approach

Use a dedicated confidential client with service accounts enabled — it is purpose-built for exactly this use case and avoids the password lifecycle problems entirely.

On the positive side, the pattern that scales best in real organizations is one client per service, one service account per client, and roles granted individually per integration. This “principle of least privilege at the identity level” mirrors good practice in cloud IAM systems generally, and it makes incident response dramatically simpler — if one service is compromised, you disable exactly one client and nothing else breaks.

Pattern: Service Mesh Trust Boundary

In a microservices architecture, each service calling another internal service authenticates with its own service account, and the receiving service checks for a specific client role before processing the request — creating a clear, auditable trust boundary between services.

Pattern: Scoped Automation Accounts

A CI/CD pipeline is given a service account with only a “deploy-app-x” role, never a general admin role, so a compromised pipeline credential cannot touch unrelated systems.

9Monitoring, Logging, and Operational Visibility

A service account you can’t observe is a service account you can’t fully trust.

Because service accounts operate without a human clicking anything, unusual behavior can slip by unnoticed unless it is deliberately monitored. Keycloak surfaces several signals worth watching in production environments.

Token
Issuance Events
Client
Login Attempts
Role
Assignment Changes

Keycloak’s admin event log can record every time a client’s roles are added or removed, and its login/token event stream shows every successful and failed client-credentials exchange. Piping these events into a centralized logging or SIEM system lets a team notice, for example, a service account suddenly requesting tokens far more often than its normal baseline — a common early sign of a leaked secret being abused by an attacker.

i
Practical Tip

Give every client a clear, descriptive name (like inventory-service or nightly-billing-job) rather than a generic one. This single habit makes audit logs vastly easier to read months later, when someone is trying to figure out exactly which service made a suspicious call.

It also helps to track metrics such as token request rate per client, average token lifetime remaining at time of use, and the count of distinct IP addresses a given client authenticates from. A service account that suddenly authenticates from a new, unexpected network location is a strong signal worth investigating immediately, since — unlike a human — a legitimate service typically runs from a small, predictable set of infrastructure.

10Real-World and Industry Examples

Service accounts of this general shape — a non-human identity with a secret and a scoped set of permissions — are not unique to Keycloak. The same underlying idea appears across the industry under different names, which helps put Keycloak’s approach in context.

PlatformEquivalent ConceptNotes
KeycloakService Account (linked to a confidential client)Uses the OAuth2 Client Credentials Grant
Google CloudIAM Service AccountA dedicated identity for applications, with its own keys and IAM roles
AWSIAM Role (assumed by an application)Grants temporary credentials to workloads instead of a permanent access key
KubernetesServiceAccount objectGives pods a token they can present to the Kubernetes API server
AzureService Principal / Managed IdentityAn application identity within Azure Active Directory

This convergence across platforms is not a coincidence — it reflects a shared, well-understood principle in identity engineering: humans and machines need different authentication mechanisms, but they can share the same underlying authorization model. Keycloak simply applies that principle using standard OAuth2/OIDC building blocks, which is part of why it integrates cleanly with so many other systems that already speak the same protocol.

Example: E-Commerce Platform

A payment-processing microservice uses a service account scoped only to “read-order-total” when it needs to confirm a purchase amount with the order service, rather than being trusted with full order-management access.

Example: Healthcare Data Pipeline

A nightly ETL job that anonymizes patient records for analytics authenticates as a service account limited strictly to the analytics database’s write endpoint, with no access to the source clinical system.

Example: SaaS Multi-Tenant Backend

A tenant-provisioning service uses its own service account to call the identity realm’s admin API when a new customer signs up, entirely separate from the service account used by the billing integration.

11Frequently Asked Questions

Q1Can a service account log in through the normal Keycloak login page?

No. A service account has no password, so it cannot be used with the interactive, browser-based login form. It can only be used through the Client Credentials Grant, called directly by the application’s backend code.

Q2Does every Keycloak client automatically get a service account?

No. Service accounts must be explicitly enabled on a client, and only confidential clients (never public clients) are allowed to have one, since only confidential clients can safely hold a secret.

Q3Can a service account be assigned to a group?

In modern Keycloak versions, yes — a service account user can be placed into groups just like a regular user, which is a convenient way to grant it a bundle of roles at once instead of assigning each role individually.

Q4What happens to the service account if I delete the client?

The linked service account user is deleted along with it, since it exists only as an extension of that specific client and has no independent life of its own.

Q5Is a service account the same thing as an “admin” account?

No. By default a service account has no special privileges at all. It only gains administrative power if an administrator explicitly assigns it administrative roles — which, per the security best practices covered earlier, should be avoided unless truly necessary.

Q6Can two different clients share the same service account?

No. The relationship is strictly one-to-one — each confidential client with service accounts enabled gets its own dedicated, uniquely named service account user.

12Summary and Key Takeaways

A Keycloak service account is, at its heart, a small but elegant solution to a very common problem: how do applications prove who they are to each other without a human typing a password? By quietly creating a dedicated, passwordless user behind every confidential client, Keycloak lets machine-to-machine communication use exactly the same trusted token infrastructure, role model, and audit trail that human logins use — no shortcuts, no shared “robot” passwords, no disabled security between internal services. Used with narrowly scoped roles, rotated secrets, and proper monitoring, service accounts become one of the most reliable building blocks for secure automation in any system built on Keycloak.

Key Takeaways

  • A service account represents an application, not a person — it is a hidden, passwordless user auto-linked to a confidential client.
  • It authenticates via the Client Credentials Grant — a direct, non-interactive exchange of client ID and secret for an access token.
  • Only confidential clients can have one — public clients cannot safely hold a secret and are excluded by design.
  • Roles must be scoped narrowly — grant only what a specific service needs, never broad administrative access “just in case.”
  • One client, one service account, one purpose — never share a single service account across multiple unrelated services.
  • Secrets need active protection — vault storage, rotation, and short token lifetimes all reduce the blast radius of a leak.
  • Monitoring matters — token issuance logs and role-change audits catch misuse that no human login screen would ever reveal.