identity management with keycloak

Identity Management with Keycloak

Back in the days when those of my generation were wild, young and free (I’m laughing), whenever programming a web application the first thing we had to think of was the authentication.

Each time it was kind of a struggle: prevent SQL injections and other kind of attacks, store user profiles and encrypted passwords, what authentication cookie should we be using, and so forth, so on.

There was very often something that made us scratch our head upon. The amount of needed work started to increase when our application had to support external identities for users, coming from Twitter, Facebook, or Google for example.

The advent of those external, global identity providers using OpenID-based authentication and authorization protocols (like OAuth) allowed us to make a giant step forward;  there was no need for our  application to store user passwords, just to mention one of the advantages. 

Things got even better when identity provider software platforms, like Keycloak, came into play; it turned out we can have our own identity provider deployed directly in our structure (either on-premises or in cloud) providing us with full control over authentication and authorization policies, storing user profiles, and federating authentication, all in one place with every aspect being adherent to top-notch security standards.

What is more, integrating Keycloak’s authentication and authorization with our applications requires as little effort as importing a dedicated connector (called adapter) in our app, so that the whole communication and token exchange behind authentication is handled for us already.

Keycloak provides user federationstrong authenticationuser managementfine-grained authorization, and more. Its features encompass:

  • Single-sign on and single-sign out
  • Login customizable themes
  • Identity brokering and social login
  • User federation
  • Administration console
  • Account management console
  • Standard protocols
  • Authorization services

In this article we’ll present what Keycloak can do and why it can be considered the Swiss army knife for almost any identity management needs.

Keycloak as an identity manager

One of the most important differences to grab when considering the adoption of Keycloak is that your users will not authenticate with your applications anymore, they will authenticate with Keycloak.

This means that, as a developer, you won’t have to deal with login forms, user authentication and user storing in your applications.

Once logged in to Keycloak, users don’t have to login again to access different applications of yours; this is single-sign on. The same is also applied to logout; Keycloak provides single-sign out, which means users only have to logout once to be logged out from all applications immediately.

Getting started with Keycloak

There are various options to get Keycloak, all available here: https://www.keycloak.org/downloads .

Although installing and configuring Keycloak would require an article on its own, we can state that probably a good balance between quick deployment and flexibility can be achieved by installing Keycloak using a container image (suitable for Docker, Podman, OpenShift and Kubernetes). 

Keycloak supports many database systems out there (on top of JPA), among which we find our beloved H2, MySQL, PostgreSQL, MariaDB, Oracle or Microsoft SQL Server

If you’re thinking to High Availability or even clustered deployment, we will be covering those topics in some minutes below.

It's all about realms

Realms are the main concept in Keycloak. A realm is a space that groups objects you can manage, like users, client applications, external identity providers, roles, and groups. 

It is important to state that the single user belongs to and logs into one single realm; this means that users belonging to a certain realm cannot log in to other realms. 

With the concept of realms, Keycloak goes in the direction of the multi-tenancy: it is possible in fact to host several realms, one per each of your customers / application / company group, all with separated users and authentication domains.

Keycloak does not impose particular limits on how many realms your deployment can define, store, and manage, in fact it can host as many realms as there is space for in the database.

Keycloak comes with one predefined realm, Master.

The Master realm is “the one ring to rule them all”, meaning it determines the overall application behaviour  for Keycloak and establishes the fallback defaults for all of the other realms to come, that may be considered as children of this one. NOTE: it is discouraged to use the Master realm for clients  and users authentication directly, as it is dedicated to configure Keycloak itself. You must create new realms in order to do that; they will be automatically set as children of Master.

At first, let’s explore the Master realm main settings, as many of them will be available the same way in child realms.

General options

The General tab in every realm presents the basic settings of it, like its displayed name (both as plain text and in HTML, useful in the realm login forms) and its status (enabled or disabled). 

There are three more settings, though, that can be of particular interest.

The Frontend URL lets you specify a URL that can be dedicated to the realm, to override the base URL for frontend requests. E.g.: if your Keycloak installation is available at https:// idp.mycompany.com, the frontend URL could be https://myrealm.idp.mykeycloak.org.

User-Managed-Access enables or disables the ability for users of the realm to access their Account Management Console, i.e. the place where they can check their activities, terminate open sessions and change their password.

Finally, the Endpoints expose the Keycloak’s Identity Provider metadata in both flavours, OpenID and SAML 2.0. These are the endpoints that you, as the identity manager administrator, will forward to external identity providers when configuring federated authentication.

Login options

The Login options provide some interesting choices too:

  • Enable or disable the registration page, as well as a link to registration on the login page.
  • Show/hide the username field on the registration form; in case it is hidden, the email field is used as username for new users.
  • Make the username field editable.
  • Enable/disable the link on login page to be clicked when users need to activate the password reset procedure.
  • Show/hide the checkbox on the login page to allow users to remain logged in between browser restarts until session expires.
  • Require users to verify their email address after initial login or after address changes are submitted.
  • Allow users to log in with their email address.
  • Allow two different users to use the same email address
  • Determine whether HTTPS required:
    • ‘None’ means HTTPS is not required for client IP addresses.
    • ‘External requests’ means localhost and private IP addresses can access without HTTPS.
    • ‘All requests’ means HTTPS is required for all IP addresses.

Email options

In this tab it is possible to configure an email service provider to use when sending out emails to users. Without setting it up, no emails can be sent by Keycloak to anybody.

Security Defenses options

This tab is divided in 2 sections: HTTP headers and brute force attacks detection.

The HTTP headers section allows settings for:

  • X-Frame-Options to XSS
  • Content-Security-Policy
  • Content-Security-Policy-Report-Only
  • X-Content-Type-Options
  • X-Robots-Tag
  • X-XSS-Protection
  • HTTP Strict Transport Security (HSTS)

while the brute force detection allows to configure detection policies (maximum number of sequential failed login attempts, permanent lockout, etc.)

Login themes

As already said, one user can log in to the realm it belongs to.

However, every realm can customize its own login form, so different realms can use different templates within the same server/cluster.

Keycloak comes with some default themes, but custom, user-made ones can be added.

Here following there is the standard Keycloak login form:

and this is the same form using a custom theme:

the theme to use is related to the realm, so different realms can use different templates within the same server/cluster.

Identity Brokering and Social Login

Owing to standard authentication protocols adoption, Keycloak is able to act as an identity broker towards virtually any external identity provider using OpenID or SAML 2.0.

By the way, it comes with out-of-the-box support for : 

  • Github
  • Facebook
  • Google
  • LinkedIn
  • Instagram
  • Microsoft
  • BitBucket
  • Twitter
  • Openshift V4
  • Openshift v3
  • Gitlab
  • PayPal
  • StackOverflow
Oh, and let’s not forget in this list (obviously) Keycloak OpenID Connect, meaning things are much straightforward when you have to federate with another Keycloak-based external identity provider.

In order for your apps to let users authenticate through Keycloak, you can leverage one of the several adapters that are directly provided:

  • Java (JBoss EAP, WildFly, Tomcat, Jetty 9, Servlet Filter, Spring Boot, Spring Security) 
  • JavaScript (client-side)
  • JavaScript Node.js (server-side)
  • C# OWIN (community)
  • Python (oidc generic)
  • Android (AppAuth generic)
  • iOS (AppAuth generic)
  • Apache HTTP Server (mod_auth_openidc)

In order for your apps to let users authenticate through Keycloak, you can leverage one of the several adapters that are directly provided:

Identity Brokering flow

To shed some light on what the authentication flow is with Keycloak when acting as an identity broker, let’s look at the following diagram: 

Source: keycloak.org
  1. The unauthenticated user requests a protected resource in a client application.
  2. The client application redirects the user to Keycloak to authenticate.
  3. Keycloak displays the login page with a list of identity providers configured in a realm.
  4. The user selects one of the identity providers by clicking its button or link.
  5. Keycloak issues an authentication request to the target identity provider and redirects the user to the identity provider’s login page. 
  6. The user provides credentials or consents to authenticate with the identity provider.
  7. Upon successful authentication by the identity provider, it redirects back to Keycloak with an authentication response. 
  8. Keycloak checks if the response from the identity provider is valid. If valid, Keycloak imports and creates a user if the user does not already exist. Keycloak may ask the identity provider for further user information if the token does not contain that information. This behavior is identity federation. If the user already exists, Keycloak may ask the user to link the identity returned from the identity provider with the existing account. This behavior is account linking. With Keycloak, you can configure Account linking and specify it in the First Login Flow. At this step, Keycloak authenticates the user and issues its token to access the requested resource in the service provider.
  9. When the user authenticates, Keycloak redirects the user to the service provider by sending the token previously issued during the local authentication. 
  10. The service provider receives the token from Keycloak and grants access to the protected resource.

User Federation

Keycloak stores and manages users. However, companies often have LDAP or Active Directory services already, that store user and credential information. Using the Administration Console, Keycloak can be linked to those external sources to validate credentials and pull in identity information.

Keycloak has built-in support to connect to existing LDAP and Active Directory servers.

It is even possible to implement your own provider if you have users in other stores, such as a relational database.

Ok, that's users. What about applications?

Applications do need authentication too in Keycloak, not only users. In Keycloak (unsurprisingly enough), applications are called “clients”. Clients can be public (no need for application-level authentication) or private, meaning within every authentication requests the client must equip the payload with its configured client id and secret (a uuid string that is materially the client password). If a client is not known by Keycloak, no authentication (and consequently no authorization) can be issued. In other words, all the applications that need authenticating with a realm must be configured as clients of that realm.

By the way, an application can allow anonymous users to navigate its resources, authenticating itself with Keycloak using its client id and secret and not asking for user login. Though, this is an implementation choice of the application’s owner.

The administration console

Using the administration console, administrators can manage all aspects of the Keycloak server, from just one place. Admins can enable and disable various features: they can

  • create and manage users, including permissions and sessions
  • configure identity brokering and user federation
  • create and manage applications and services
  • define fine-grained authorization policies
One of the most useful aspects in managing users coming from external identity providers is the attribute mapping. Usually user attributes exposed by external providers do not match one to one with the attributes natively present or configured within our internal users management. On the first login with an external identity provider, the user profile gets imported in Keycloak, which maps incoming attributes with the configured ones. The good news is, the attribute mapping is a feature of the single identity provider configured in Keycloak, meaning every identity provider Keycloak is brokering for can have its own mapping rules.

The Account Management console

If allowed by the realm (see above), users can manage their own accounts through the Account Management Console. 

Source: keycloak.com

The Account Management Console offers profile update, password change, and it’s ready for two-factor authentication, made available via apps like Google Authenticator or Microsoft Authenticator. Users can also manage sessions as well as view the activity history for the account.

If social login or identity brokering is enabled, users can also link their accounts to additional providers. This allows them to authenticate to the same account with different identity providers.

The Protocols

Keycloak is based on solid, standard protocols: as we already said, it supports SAML as well as OpenID Connect and OAuth 2.0.

SAML is an open standard for exchanging authentication and authorization data between parties, in particular, between an identity provider and a service provider.  It is an XML-based markup language for security assertions (statements that service providers use to make access-control decisions).

OAuth 2.0, which stands for “Open Authorization”, is a standard designed to allow a website or application to access resources hosted by other web apps on behalf of a user. It replaced OAuth 1.0 in 2012 and is now the de facto industry standard for online authorization.

OpenID Connect is the 3rd generation of OpenID technology. It is an authentication layer on top of the OAuth 2.0 authorization framework. It allows computing clients to verify the identity of an end user based on the authentication performed by an authorization server. On top of that, it provides for obtaining the basic profile information about the end user. In technical terms, OpenID Connect specifies a RESTful HTTP API, using JSON as a data format.

Did somebody Say Cluster?

From the Keycloak documentation:

Before deploying Keycloak in a production environment you need to decide which type of operating mode you are going to use.

  • Will you run Keycloak within a cluster?
  • Do you want a centralized way to manage your server configurations?

Thus, let’s see which operation modes are available with Keycloak.

Standalone mode

If we want to run just one Keycloak instance, we’re talking about the standalone operating mode.

It is not usable for clustered deployments and it is not the recommended way to deploy it in production, as it constitutes a single point of failure, but it is a good way to explore the features and integrate Keycloak into your development server array.

Standalone Clustered mode

If we want to run Keycloak in a cluster instead, the easiest operating mode to deploy is standalone clustered. This method involves having:

  • a Keycloak instance on each machine participating in the cluster, and a shared database connection.
  • a database connection shared between all Keycloak instances
  • a load balancer in front of the cluster

The easier initial configuration comes at a cost though; to make a configuration change it will be necessary to edit each instance on each machine

Domain Clustered mode

If we’re looking for a way to manage and publish configurations for all your Keycloak servers from one place, we’re talking about the domain clustered mode.

The point to get here is that the choice between a clustered deployment and standalone servers has to do by all means with how your servers are managed, and by no means with how much they can service end user requests. In synthesis, in this context, HA functionality is orthogonal to running standalone servers or a cluster. That is, a group of standalone servers can be configured to form an HA cluster. The domain and standalone clustered modes determine how the servers are managed, not what capabilities they provide.

 This operation mode involves 2 server roles: domain controller and host controller.

Domain controller

In domain clustered mode, there is one process that is responsible for managing, storing and providing the general configuration to each Keycloak node in the cluster; this process is the domain controller. The presence of this process within one of the cluster nodes promotes it to domain controller. In short, this process is the central point in the cluster from which nodes get their configuration.

Host controller

One machine in the cluster may allocate one or more than one instance, the host controller is the process in charge of managing such instances. The domain controller dialogues with host controllers to manage the cluster. Usually, in order to spare resources, even the domain controller runs a host controller itself and thus also at least one Keycloak server instance. At startup, every host controller obtains its configuration from the domain controller and it starts as many Keycloak instances as it was configured to do.

Conclusions

In this article we covered the key features of Keycloak, an open source-based identity management system that righteously we can consider the Swiss army knife for authentication, authorization and identity brokering. Keycloak is so feature-rich, each of the features mentioned in this article would deserve to be  exhaustively described in a dedicated article.

Stay tuned for other SpazioCodice articles! See you!

Do you want to know more? Don’t hesitate to contact us

Share this post

Leave a Reply