Key Takeaways
Move password handling out of applications and centralize identity at Keycloak
One identity service. Keycloak is an open source identity and access management system: it authenticates users, manages sessions, and issues tokens so individual applications do not need to collect or store user passwords. A realm is an isolated tenant, with its own users, applications, and settings. Separate realms can serve, for example, employees and customers on one Keycloak installation.
Less credential exposure. Once a user signs in, applications receive tokens that grant specific forms of access rather than the user's credentials. This also lets an administrator change authentication requirements, such as adding a second factor, without rewriting every application. Keycloak supports single sign-on, user self-service, and connections to existing identity stores, while offering extension points for requirements its standard configuration does not cover.
The architectural gain is not merely fewer login screens. It creates a central place to apply identity policy, which resembles the separation of control planes from individual services in distributed systems. That can reduce inconsistent security decisions across a sprawling application estate. Centralization also creates concentration risk: if the identity service or its administrative account is compromised, many applications may be affected at once. The book's approach therefore works best when paired with careful isolation, strict administrative access, and resilient operations. Convenience and risk move together when one service becomes the gatekeeper.
Use authorization code, not password collection, to connect modern apps
Separate identity from permission. OAuth 2.0 is a framework for granting an application limited access to a resource; OpenID Connect adds a standardized way to authenticate a person. In the Authorization Code flow, the user's browser visits Keycloak to sign in, then the application exchanges a short-lived code for tokens. The ID token communicates who authenticated; the access token is presented to a service to request permission.
Avoid shortcuts that expose credentials. The book warns against the Implicit flow and the Resource Owner Password Credentials flow for modern applications. The latter has an application collect the user's password directly, undermining centralized authentication and stronger login methods. For browser and native applications, use Authorization Code with Proof Key for Code Exchange (PKCE), which protects the code if it is intercepted. SAML remains useful when required by existing systems.
The distinction between identity and delegated authority prevents a common category error: a token that proves a user signed in does not automatically authorize every operation that user could perform. The redirect also gives people a clearer signal about which service is asking for credentials. This is a useful security boundary, not just protocol ceremony. Yet standards do not make an implementation safe by themselves. Redirect validation, PKCE, token handling, and maintained libraries still matter, so the practical advice is to use a well-supported implementation rather than reproduce the flow from memory.
Give each access token only the audience, roles, and scopes its job requires
Narrow the token's reach. An access token is a credential a client presents to a resource server. Keycloak can constrain where that token is accepted through its audience, which names intended services; roles, which describe permissions available to the client; and scopes, which represent requested kinds of access. A backend should check that the token is meant for it, not simply accept any valid token.
Trim claims deliberately. By default, a new configuration may include more roles than a production client needs. Disabling Full Scope Allowed and granting only necessary roles reduces excess permissions and token size. Optional scopes can support incremental access: an app asks for a new permission only when a feature needs it, and Keycloak can request user consent. Services can validate signed JWTs locally or query Keycloak's introspection endpoint, trading lower latency for a live status check.
This is least privilege translated into token design. A signed token is easy to pass around, which makes accidental overreach particularly tempting: if every service trusts the same broad claims, one exposed token may unlock more than its original task. Audience checks add a useful boundary, while scopes make delegation legible to users and administrators. Local JWT validation is efficient, but it can lag behind a session revocation until token expiry. Choosing between local checks and introspection is therefore a deliberate consistency-versus-latency decision, not a purely technical preference.
Choose the browser-to-backend boundary before choosing the Keycloak client
Architecture determines exposure. A server-side web app can keep client credentials and tokens on the server. A single-page application with a same-domain backend can use that backend to establish a session. When a browser app must reach external APIs, the book favors an intermediary backend, often called a backend for frontends: it holds tokens and makes API requests, rather than exposing refresh tokens to browser code.
Public clients need extra care. A browser or mobile app cannot safely keep a client secret. If a single-page app obtains tokens directly, use Authorization Code with PKCE, short-lived tokens, refresh-token rotation, and strong protection against cross-site scripting. Native apps should authenticate through an external browser or supported in-app browser, not an embedded login page that can expose credentials. Device authorization fits devices without a usable browser.
The key design question is where a durable secret can actually be protected. Client-side code is observable by its user, so labeling a browser app confidential does not make it so. The intermediary pattern shifts token custody to a server and also avoids some cross-origin complications, at the cost of another service to build and operate. This is a classic systems tradeoff: reduce exposure in one layer by accepting complexity in another. Sensitivity of the data, deployment capacity, and threat model should determine which cost is acceptable.
Match authorization policy to whether you govern users, clients, or context
Choose the permission model by question. Role-based access control (RBAC) grants permissions through roles; group-based access control (GBAC) organizes users into groups and can assign roles to those groups. OAuth scopes address a different question: whether a client may access a user's resources on that user's behalf. Attribute-based access control (ABAC) evaluates claims about the user or authentication context, allowing more fine-grained decisions.
Keep roles interpretable. Realm roles make sense when the role has the same meaning across applications; client roles are specific to one application. Avoid turning every fine-grained permission into a role, which can make administration unwieldy. Keycloak Authorization Services can centralize policy decisions around named resources, allowing applications to ask whether access is allowed without hard-coding each policy. Tokens can carry granted permissions so services may evaluate them locally.
The distinctions help teams identify the subject of a decision. RBAC often answers what a user may do, while OAuth scopes answer what a client may do on the user's behalf; ABAC can incorporate attributes and context. Confusing these questions leads to permissions that are either too broad or difficult to explain. Centralized policy can make changing rules easier, but it does not eliminate governance work. Resource names, policy ownership, and token contents still need clear design, or the central authorization layer simply relocates complexity rather than reducing it.
Federate existing identities before forcing every user into a new account
Connect rather than replace. Keycloak can work with local users, LDAP or Active Directory, and external identity providers such as social login services. User federation is the connection to an external identity store. With LDAP, Keycloak can import user records and keep them synchronized, or delegate credential checks to the directory. A read-only configuration preserves LDAP as the source of truth; a writable one can send changes back.
Broker external sign-in. With identity brokering, Keycloak acts as an intermediary: a user authenticates at an OpenID Connect or SAML provider, and Keycloak uses the returned identity information to create or update a user in its own realm. LDAP mappers can also bring in groups and roles. User attributes and protocol mappers let administrators decide which additional information becomes available to applications in tokens or user information responses.
Federation treats identity as an ecosystem rather than a database migration project. That can preserve established accounts and avoid making users maintain another password, while giving applications a more consistent interface. The tradeoff is that synchronization introduces questions of authority: which system owns a field, how quickly updates propagate, and what happens when a source is unavailable? Explicitly deciding those rules is more important than simply connecting directories. Claims should also be minimized, since copying a large identity profile into every application token can create privacy and exposure costs.
Make stronger authentication a configurable flow, not an application rewrite
Compose authentication steps. A Keycloak authentication flow is a sequence of executions, such as checking an existing session, collecting a password, or requesting a second factor. Administrators can configure whether a step is required, optional, or conditional. This makes it possible to adapt login behavior without embedding each mechanism in every application.
Add factors with different strengths. Passwords are stored as salted, repeatedly hashed values, but remain vulnerable to theft, phishing, and reuse. Keycloak supports one-time passwords, commonly time-based codes that expire after a short window, as a second factor. WebAuthn uses public-key cryptography between a user's device and the service, avoiding a shared OTP secret and enabling security-key or biometric verification. The account console lets users manage profile information, credentials, and active sessions.
A configurable flow turns authentication into policy that can evolve independently of application code. That is valuable because threat levels differ: a routine sign-in and a sensitive action need not always demand identical friction. Password hashing protects stored credentials, but it cannot prevent a user from being tricked into disclosing one. Cryptographic authenticators reduce some phishing exposure, though recovery procedures and device loss remain operational challenges. Strong authentication is therefore a whole account lifecycle, including enrollment, fallback, and revocation, not merely a checkbox for a second factor.
Set token and session lifetimes as one security and usability budget
Tokens depend on sessions. Keycloak tracks a user-level single sign-on session and client sessions for individual applications. Session idle limits end an inactive session; maximum lifetime sets a hard stop. ID and access tokens are short-lived, five minutes by default in the book's example, while refresh tokens can obtain replacements as long as their associated sessions remain valid.
Plan for leakage and logout. Short token lifetimes reduce the time a stolen bearer token can be used, but frequent refreshes add work for clients and Keycloak. Refresh-token rotation invalidates a token after use, helping reveal reuse. Administrators can end sessions or apply a not-before revocation time. For ordinary sign-out, short token lifetimes may be sufficient; where immediate sign-out is required, back-channel logout can notify participating applications.
Lifetime settings expose a three-way tension among user friction, infrastructure load, and exposure after theft. Treating tokens and sessions separately can create a false sense of control: a locally verified JWT may remain within its stated expiry even after its backing session is ended. Introspection can provide fresher validity information, but adds network dependency and latency. A sound policy begins with the consequences of unauthorized use, then sets a tolerable window and tests how the chosen clients behave when refresh, revocation, or logout occurs.
Use maintained protocol integrations before writing your own security plumbing
Integrate at the right layer. Applications can embed an OpenID Connect library or use a proxy in front of the application to handle authentication. Embedded integrations keep the app self-contained; proxies can help protect legacy software or centralize configuration. The book surveys options across Go, Java, JavaScript, Node.js, and Python, and recommends favoring libraries or framework support that are widely used, maintained, and aligned with current standards.
Customize only where needed. Keycloak's Service Provider Interfaces (SPIs) allow custom behavior, including themes, authentication mechanisms, user storage, and event handling. A custom provider is packaged for Keycloak to load. The flexibility is powerful, but a custom integration or extension creates code that must be tested and maintained. Use a standard library for protocol mechanics; reserve extensions for requirements configuration cannot meet.
Security protocols are deceptively easy to partially implement. A happy-path login demo can omit protections that matter under attack, while mature libraries spread the maintenance burden across a broader community. The same principle applies inside Keycloak: extension points make adaptation possible, but every bespoke provider becomes part of the trusted computing base. Proxies can also concentrate policy while obscuring behavior from application teams. The sensible default is not maximal customization; it is the smallest supported integration that meets the system's actual needs.
Production security lives in URLs, TLS, databases, clusters, and updates
Make the deployment trustworthy. Production Keycloak should use HTTPS, a fixed public hostname, and a real database rather than the simple development database. In a cluster, every node should advertise the same issuer and endpoints; a reverse proxy distributes traffic and can preserve session affinity. Keycloak's caches share session state, while database, proxy, and cluster settings affect availability and performance.
Protect the system around the login page. Restrict administrative access, secure database credentials and backups, encrypt data in transit and at rest, and limit unnecessary network paths. Rotate signing keys by activating new keys while retaining old ones long enough to verify existing tokens. Keep Keycloak and its dependencies updated. Keycloak helps with authentication, but applications still need authorization, input protections, monitoring, and their own security maintenance.
Identity security is a property of the deployment, not just the login protocol. A correct token flow cannot compensate for a database that an attacker can rewrite, an untrusted hostname that poisons password-reset links, or a cluster that accepts unknown nodes. This is defense in depth in a concrete form: each layer limits the damage if another fails. High availability also deserves security scrutiny, since replication can spread both legitimate state and misconfiguration. Load testing, failover testing, and access reviews are part of identity engineering, not post-launch housekeeping.
Analysis
This book is best understood as an implementation guide organized around a practical progression: start a Keycloak instance, secure a sample frontend and API, learn the standards that make the connection work, then prepare the identity service for real users and production traffic. Its main audience is developers and operators who need to make identity decisions across different application architectures, not readers seeking a purely theoretical account of OAuth or security.
The central design lesson is separation of responsibility. Keycloak handles user authentication and issues tokens; applications and services decide what those tokens permit. That separation is only useful when the token is constrained to the right service and permissions, and when applications validate it correctly. The book repeatedly connects protocol details to deployment choices: a browser cannot protect a client secret, a cluster needs a stable issuer, and a short token lifetime means more refresh work. Security is presented as a set of interacting tradeoffs rather than one feature to enable.
The strongest practical feature is its breadth. It covers client and resource-server integrations, LDAP and identity providers, multiple authorization models, stronger authentication, session management, customization, and high availability. That breadth also creates a summarization challenge: individual configuration procedures matter to practitioners, but listing them would obscure the reusable principles. The most valuable through-line is to use standards and maintained libraries, keep credentials away from applications, grant narrowly scoped access, and design operations around the consequences of token or server compromise.
The material reflects the Keycloak and ecosystem context at publication in 2021. Its architectural principles remain useful, but version-specific commands, adapter recommendations, and security guidance should be checked against the software version actually deployed. Keycloak centralizes identity; it does not make applications secure by association. The application, database, proxy, and operational process remain part of the security boundary.
People Also Read
Glossary
Realm
Isolated identity tenantA realm is an isolated administrative space in Keycloak, containing its own users, clients, roles, identity providers, and authentication settings. One Keycloak installation can host multiple realms, such as separate spaces for employees and customers. Users authenticate through the realm to which their account belongs.
Authorization Code flow
Browser-mediated token exchangeA protocol flow in which an application sends a user's browser to an identity provider for authentication or authorization. After approval, the application receives a short-lived authorization code and exchanges it for tokens. The code exchange keeps tokens out of the initial browser redirect and is the recommended foundation for many web and native application integrations.
OpenID Connect
Identity layer over OAuthAn authentication protocol built on OAuth 2.0. It standardizes how an application requests and receives information about an authenticated user, most notably through an ID token. OpenID Connect also defines discovery metadata and a UserInfo endpoint, helping applications integrate with different identity providers through common interfaces.
Proof Key for Code Exchange (PKCE)
Authorization-code interception defenseAn OAuth 2.0 extension that binds an authorization request to the later exchange of its code. The client creates a secret verifier and uses a derived challenge in the initial request. If an attacker intercepts the authorization code, the attacker cannot exchange it without the verifier. The book recommends PKCE for browser-based and native applications.
Client scope
Reusable token permissions or claimsA Keycloak configuration object that groups protocol mappers, role permissions, and related token settings for use by clients. A client can receive scopes by default or request optional scopes. Scopes can control what claims appear in tokens and can represent permissions that a user may be asked to approve.
User federation
Connection to external identity storesKeycloak's integration with an external user directory, such as LDAP or Active Directory. Depending on its configuration, Keycloak can import user records, synchronize changes, write selected changes back, or delegate credential validation to the external store. Mappers control how directory attributes, groups, and roles correspond to Keycloak data.
Authentication flow
Configurable sequence of login stepsA Keycloak-defined sequence of authentication executions and nested subflows. Steps can collect credentials, reuse an existing session, or request another factor. Their settings determine whether a step is required, optional, or conditional. Administrators can adapt a flow or create a copy to meet a realm's authentication requirements.
WebAuthn
Public-key device authenticationA browser-mediated protocol that lets a server register and use an authenticator, such as a security key or supported device, through public-key cryptography. The server stores a public key rather than sharing a secret with the authenticator. Keycloak can use WebAuthn for a second factor and for passwordless or biometric authentication, depending on configuration and device support.
Service Provider Interface (SPI)
Keycloak extension contractA defined interface through which Keycloak loads alternative or custom implementations of a capability. A provider implements the feature, while a provider factory manages its creation and lifecycle. SPIs support extensions such as custom authentication, user storage, event listeners, and theme behavior. Custom providers require packaging and operational maintenance.
FAQ
What's Keycloak - Identity and Access Management for Modern Applications about?
- Identity Management Focus: The book is a comprehensive guide on using Keycloak, an open-source tool, for identity and access management in modern applications.
- Protocol Coverage: It explains industry-standard protocols like OAuth 2.0 and OpenID Connect, detailing their use in authentication and authorization.
- Practical Examples: Includes practical examples and code snippets, making it suitable for developers, system administrators, and security engineers.
Why should I read Keycloak - Identity and Access Management for Modern Applications?
- Comprehensive Resource: It serves as a complete resource for implementing identity and access management using Keycloak, from basic concepts to advanced configurations.
- Hands-On Approach: Offers practical examples and step-by-step instructions, allowing readers to apply what they learn to their projects.
- Expert Insights: Authored by Stian Thorgersen, a Keycloak expert, providing valuable insights into best practices and advanced configurations.
What are the key takeaways of Keycloak - Identity and Access Management for Modern Applications?
- Understanding Keycloak: Readers will gain a solid understanding of Keycloak's capabilities, including user management and authentication flows.
- Integration Techniques: The book outlines various integration techniques for different programming languages and frameworks.
- Security Best Practices: Emphasizes the importance of using OAuth 2.0 and OpenID Connect for secure application access.
What are the best quotes from Keycloak - Identity and Access Management for Modern Applications and what do they mean?
- Delegating Authentication: "By delegating authentication to Keycloak, your applications do not need to worry about different authentication mechanisms." This simplifies authentication processes.
- Lightweight Solution: "Keycloak is a lightweight and easy-to-install solution." Highlights its accessibility for developers.
- Use Established Libraries: "You should rely on well-known and widely used libraries." Stresses the importance of using established libraries for security.
How do I install Keycloak as described in Keycloak - Identity and Access Management for Modern Applications?
- Installation Options: Keycloak can be installed via Docker, locally with OpenJDK, or on Kubernetes, each with specific instructions.
- Docker Installation: Use the command
$ docker run -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin -p 8080 quay.io/keycloak/keycloakfor a quick setup. - Local Installation: Requires OpenJDK, downloading Keycloak distribution, and creating an admin account using provided scripts.
What is the difference between OAuth 2.0 and OpenID Connect as explained in the book?
- OAuth 2.0 for Authorization: Primarily an authorization framework allowing third-party applications limited access to user accounts.
- OpenID Connect for Authentication: Builds on OAuth 2.0 by adding an authentication layer, verifying user identity.
- Token Types: OAuth 2.0 issues access tokens, while OpenID Connect issues ID tokens containing user identity information.
How can I secure my first application using Keycloak?
- Sample Application: The book provides a sample application with a frontend web app and a backend REST API for demonstration.
- Configuration Steps: Key steps include registering the application with Keycloak and configuring client settings.
- Testing Security: Test security by accessing protected resources to ensure only authenticated users gain access.
What are the different application types I can secure with Keycloak?
- Web Applications: Secures traditional server-side web applications and modern single-page applications (SPAs).
- Mobile Applications: Explains securing native and mobile applications using the Authorization Code flow with PKCE.
- REST APIs: Protects REST APIs by requiring access tokens for secure client-service communication.
How does Keycloak handle user management?
- User Creation and Management: Provides an admin console for managing users, including creating users and assigning roles.
- Integration with External Directories: Integrates with LDAP and Active Directory for seamless user management.
- Self-Service Features: Users can manage their accounts through the Keycloak account console.
What are the security best practices when using Keycloak?
- Use Strong Authentication: Emphasizes enabling two-factor authentication and using secure passwords for admin accounts.
- Regular Updates: Keeping Keycloak updated is crucial for maintaining security.
- Token Management: Implement short expiration times for tokens and use refresh tokens securely.
How can I extend Keycloak's functionality?
- Custom Providers: Create custom providers and mappers to extend Keycloak's capabilities.
- Themes and UI Customization: Supports theming for customizing login pages and user interfaces.
- Integration with Other Services: Integrate Keycloak with other services for a comprehensive identity management solution.
How does Keycloak manage user sessions?
- Session Tracking: Creates server-side sessions to track user activity and maintain authentication state.
- Session Lifetimes: Configurable session lifetimes help reduce the risk of session hijacking.
- Active Session Management: Provides tools for administrators to view and manage active sessions.
Download PDF
Download EPUB
.epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.