Home Cloud & Networking Keycloak - Identity and Access Management for Modern Applications

Keycloak - Identity and Access Management for Modern Applications

By Stian Thorgersen , Pedro Igor Silva
books-svg-icon Book
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Getting Started with Keycloak
About this book
Implementing authentication and authorization for applications can be a daunting experience, often leaving them exposed to security vulnerabilities. Keycloak is an open-source solution for identity management and access management for modern applications, which can make a world of difference if you learn how to use it. Keycloak, helping you get started with using it and securing your applications. Complete with hands-on tutorials, best practices, and self-assessment questions, this easy-to-follow guide will show you how to secure a sample application and then move on to securing different application types. As you progress, you will understand how to configure and manage Keycloak as well as how to leverage some of its more advanced capabilities. Finally, you'll gain insights into securely using Keycloak in production. By the end of this book, you will have learned how to install and manage Keycloak as well as how to secure new and existing applications.
Publication date:
June 2021
Publisher
Packt
Pages
362
ISBN
9781800562493

 

Chapter 1: Getting Started with Keycloak

If you are new to Keycloak, this chapter will quickly get you up to speed. We'll start with a brief introduction to Keycloak. Then, you will find out how easy it is to install Keycloak and get it up and running. After we have started Keycloak, you will learn about the Keycloak admin console, which provides a great interface for managing and configuring Keycloak. Finally, we'll take a quick look at the Keycloak account console as well, which lets users of your applications manage their own accounts.

By the end of this chapter, you will know how to get started with the Keycloak server, and understand how you can use the Keycloak admin console to manage Keycloak. You will learn how to prepare Keycloak with an example user in order to get started securing your first application in the next chapter.

In this chapter, we're going to cover the following main topics:

  • Introducing Keycloak
  • Installing and running Keycloak
  • Discovering the Keycloak admin and account consoles
 

Technical requirements

For this chapter, in order to run Keycloak, you will need to have Docker (https://www.docker.com/) or JDK 8+ (https://openjdk.java.net/) installed on your workstation.

Check out the following link to see the Code in Action video:

https://bit.ly/3nRLgng

 

Introducing Keycloak

Keycloak is an open source Identity and Access Management tool with a focus on modern applications such as single-page applications, mobile applications, and REST APIs.

The project was started in 2014 with a strong focus on making it easier for developers to secure their applications. It has since grown into a well-established open source project with a strong community and user base. It is used in production for scenarios ranging from small websites with only a handful of users up to large enterprises with millions of users.

Keycloak provides fully customizable login pages, including strong authentication, as well as various flows, such as the recovery of passwords, requiring users to regularly update the passwords, accepting terms and conditions, and a lot more. All of this without any need to add anything to your applications, or any coding at all. All pages visible to your users support custom themes, making it very easy to modify the look and feel of the pages to integrate with your corporate branding and existing applications.

By delegating authentication to Keycloak, your applications do not need to worry about different authentication mechanisms, or how to safely store passwords. This approach also provides a higher level of security as applications do not have direct access to user credentials; they are instead provided with security tokens that give them only access to what they need.

Keycloak provides single sign-on as well as session management capabilities, allowing users to access multiple applications, while only having to authenticate once. Both users themselves and administrators have full visibility to where users are authenticated, and can remotely terminate sessions when required.

Keycloak builds on industry standard protocols supporting OAuth 2.0, OpenID Connect, and SAML 2.0. Using industry standard protocols is important from both a security perspective and in terms of making it easier to integrate with existing and new applications.

Keycloak comes with its own user database, which makes it very easy to get started. You can also easily integrate with existing identity infrastructure. Through its identity brokering capabilities, you can plug in existing user bases from social networks, or other enterprise identity providers. It can also integrate with existing user directories, such as Active Directory and LDAP servers.

Keycloak is a lightweight and easy-to-install solution. It is highly scalable and provides high availability through clustering capabilities. For additional redundancy, Keycloak also supports clustering to multiple data centers.

A lot of effort has gone into making Keycloak usable out of the box, supporting common use cases, but, at the same time, it is highly customizable and extendable when needed. Keycloak has a large number of extension points where you can implement and deploy custom code to Keycloak to modify existing behavior or add completely new capabilities. Examples of extensions that can be written to Keycloak include custom authentication mechanisms, integrations with custom user stores, and the custom manipulation of tokens. You can even implement your own custom login protocols.

This section was a very brief introduction to the features and capabilities of Keycloak. As this book aims to give you a practical guide to Keycloak, we will come back to many of these features in later chapters, where you will learn firsthand how you can put these to use.

 

Installing and running Keycloak

In this section, you will quickly learn how to install and run Keycloak. Once you have Keycloak up and running, we will take a look at the Keycloak admin console and the Keycloak account console.

Keycloak provides a few options on how it can be installed, including the following:

  • Running as a container on Docker
  • Installing and running Keycloak locally (which will require a Java virtual machine, such as OpenJDK)
  • Running Keycloak on Kubernetes
  • Using the Keycloak Kubernetes operator

If you already have Docker installed on your workstation, this is the recommended approach as it is simpler to get up and running this way.

If you don't have Docker installed, it is easier to get started by installing and running it locally. The only dependency required is a Java virtual machine.

Keycloak can also be easily deployed to Kubernetes, where you have the option of using the Keycloak Kubernetes Operator, which makes installation, configuration, and management even simpler. We are not going to provide instructions for Kubernetes in this book, as we instead want to focus on Keycloak and its features. If you are interested in knowing how to run Keycloak on Kubernetes, then the Keycloak website provides great Getting started guides at https://www.keycloak.org/getting-started.

In the next section, we will look at how you can run Keycloak as a container on Docker. If you prefer to run it locally, you can skip to the section titled Installing and running Keycloak with OpenJDK.

Running Keycloak on Docker

With Docker, it is very easy to run Keycloak as you don't need to install a Java virtual machine yourself, nor do you have to download and extract the Keycloak distribution.

To run Keycloak on Docker, simply execute the following command:

$ docker run -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin -p 8080 quay.io/keycloak/keycloak

As Keycloak does not ship with a default admin account, passing the environment variables, KEYCLOAK_USER and KEYCLOAK_PASSWORD, makes it easy to create an initial admin account. We are also using –p 8080 to publish the port used by Keycloak to the host, so as to make it easy to access Keycloak.

After a few seconds, you will see a message along the lines of the following, meaning Keycloak has started successfully:

Figure 1.1 – Start up message

Figure 1.1 – Start up message

You can verify that Keycloak is running by opening http://localhost:8080.

Congratulations! You now have Keycloak running as a Docker container and can get started with trying Keycloak out by first discovering the Keycloak admin and account consoles.

Installing and running Keycloak with OpenJDK

As Keycloak is implemented in Java, it is easy to run Keycloak on any operating system without the need to install additional dependencies. The only thing that you need to have installed is a Java virtual machine, such as OpenJDK.

In the next section, we will install OpenJDK, which is required before running Keycloak. If you already have a Java virtual machine installed, you can skip the next section and go directly to the section entitled Installing Keycloak.

Installing OpenJDK

The best way of installing OpenJDK depends on the operating system you are using. Most Linux distributions, for example, include OpenJDK packages in the default repositories.

By way of an example, on Fedora, you can install OpenJDK by executing the following command:

$ sudo dnf install java-latest-openjdk

For instructions specific to your operating system, use one of the following URLs to find the relevant instructions:

Another simple way to install OpenJDK is to download one of the ready builds at https://jdk.java.net/. Open this page in your browser and then click on the JDK 15 link next to Ready for use. Download the build for your operating system, and then extract it to a suitable location. Once extracted, set the JAVA_HOME environment variable to point to the extracted directory.

The following screenshot shows an example of installing a ready build of OpenJDK on Linux:

$ mkdir ~/kc-book
$ cd ~/kc-book
$ tar xfvz ~/Downloads/openjdk-14.0.2_linux-x64_bin.tar.gz
$ export JAVA_HOME=~/kc-book/jdk-14.0.2
$ $JAVA_HOME/bin/java -version

The last command (java –version) verifies that Java is working properly.

Now that you have OpenJDK installed, we will move on to installing Keycloak.

Installing Keycloak

Once you have the Java virtual machine installed on your workstation, the next step is to download the distribution of Keycloak from the Keycloak website. Open https://www.keycloak.org/downloads, and then download either the ZIP or the TAR.GZ archive of the server (standalone server distribution). Once downloaded, simply extract this archive to a suitable location.

The following screenshot shows an example of installing Keycloak on Linux:

$ cd ~/kc-book
$ unzip ~/Downloads/keycloak-11.0.1.zip
$ cd keycloak-11.0.1
$ export KC_HOME=~/kc-book/keycloak-11.0.1

Before starting Keycloak, we will create an initial admin account.

Creating an admin account

Keycloak does not ship with a default admin account. This is to prevent anyone from running Keycloak with a default username and password in production.

This means that prior to using Keycloak, you need to create an initial admin account.

To create an admin account on Linux or macOS, execute the following command in a terminal:

$ cd $KC_HOME
$ bin/add-user-keycloak.sh -u admin -p admin

On Windows, execute the following command:

> cd %KC_HOME%
> bin\add-user-keycloak.bat -u admin -p admin

Important note

For production systems, you should obviously use a more secure password, including strongly considering using strong authentication, especially for the admin account. Later in the book, we will cover how you can easily enable two-factor authentication with Keycloak.

You are now ready to start Keycloak, which we will cover next.

Starting Keycloak

Once you have installed Keycloak and created the initial admin account, it's easy to start Keycloak.

On Linux or macOS, start Keycloak with the following command:

$ cd $KC_HOME
$ bin/standalone.sh

Or, on Windows, execute the following command:

> cd %KC_HOME%
> bin\standalone.bat

After a few seconds, you will see a message along the lines of the following, meaning Keycloak has started successfully:

Figure 1.2 – Start up message

Figure 1.2 – Start up message

You can verify that Keycloak is running by opening http://localhost:8080.

Congratulations! You now have Keycloak running on your workstation and can get started with trying Keycloak out by first discovering the Keycloak admin and account consoles.

 

Discovering the Keycloak admin and account consoles

In this section, we will take a look at the Keycloak admin and account consoles. The admin console is an extensive console that allows you to configure and manage Keycloak. The account console, on the other hand, is there to allow your end users to manage their accounts.

Getting started with the Keycloak admin console

In this section, you will learn how to log in to the Keycloak admin console as well as learn how to set up the basic configuration needed to secure your first application.

The Keycloak admin console provides an extensive and friendly interface for administrators and developers to configure and manage Keycloak.

To access the admin console, open http://localhost:8080/auth/admin/ in a browser. You will be redirected to the Keycloak login pages, where you can log in with the admin username and password you created in the previous section while installing Keycloak.

Once you have logged in, you will see the configuration for the master realm in Keycloak, as shown in the following screenshot:

Figure 1.3 – The Keycloak admin console

Figure 1.3 – The Keycloak admin console

You will learn a lot more about the admin console throughout the book, but let's go through a few steps to make your Keycloak application ready to start securing applications.

Creating and configuring a realm

The first thing you will want to do is create a realm for your applications and users. Think of a realm as a tenant. A realm is fully isolated from other realms, it has its own configuration, and its own set of applications and users. This allows a single installation of Keycloak to be used for multiple purposes. For example, you may want to have one realm for internal applications and employees, and another realm for external applications and customers.

To create a new realm, hover your mouse over the realm selector in the top-left corner (just below the Keycloak logo). When hovering your mouse over the realm selector, you will see a list of realms, including a button to create a new realm. Click on the Add realm button:

Figure 1.4 – Realm selector

Figure 1.4 – Realm selector

On the next page, enter a name for the realm. As the name is used in URLs, the name should ideally not use special characters that need escaping in URLs (such as spaces). Once created, you can set a human friendly display name. For example, use myrealm for the name, and My Realm for the display name.

Creating a user

Once you have created the realm, let's create the first user in the realm:

  1. From the left-hand menu, click on Users, and then click on Add User.
  2. Enter a memorable username, and also enter a value of your choice for email, first name, and last name.

    The Email Verified option can be selected by an administrator if they know this is the valid email address for the user.

  3. Required User Actions allows an administrator to require a user to perform some initial actions on the next login; for example, to require the user to review their profile, or to verify their email address.
  4. Remember to click on Save after you have completed the form:
Figure 1.5 – The Add user form

Figure 1.5 – The Add user form

A user has a few standard built-in attributes, such as first name, but it is also possible to add any custom attributes through the Attributes tab.

Before the user can log in, you have to create an initial temporary password. To do this, click on the Credentials tab. In the Set Password section, enter a password and click Set Password.

If the Temporary option is enabled, the user is required to change the password when logging in for the first time. In cases where an administrator creates the user, this makes a lot of sense.

Creating a group

Next, let's create a group and add the user we previously created to the group. From the menu on the left-hand side, click on Groups, and then click on New.

Enter a name for the group, for example, mygroup, and then click on Save.

Once you have created the group, you can add attributes to the group. A user inherits all attributes from a group it belongs to. This can be useful if, for example, you have a group for all employees in an office and want to add the office address to all employees in this group.

You can also grant roles to a group, which again is inherited by all members of the group.

To add the user to the group, go back to the Users page. Click View all users and select the user you created previously.

Next, click on the Groups tab. In the right-hand column, select the group you created previously and click on Join to add the user to the group.

Creating a global role

To create a global role, click on Roles in the menu on the left-hand side, and then click on Add Role. Enter a role name, for example, myrole. You can also add a description to the role, which can be especially useful if there are other administrators.

Any role in Keycloak can be turned into a composite role, allowing other roles to be added to the role. A user who is granted a composite role will dynamically be granted all roles within the composite role. Composite roles can even contain other composite roles. This feature can be very powerful, but, at the same time, should be used with some care. Composite roles can be a bit difficult to manage, and can also have a performance overhead if overused, especially if there are many layers of composite roles.

To add the user to the role, go back to the Users page. Click View all users and select the user you created previously.

Next, click on the Role Mappings tab. In the left-hand column, select the role you created previously and click on Add selected to add the user to the role.

You have now created all the required initial configuration to get started securing your first application, but first let's take a look at the Keycloak account console, which lets users manage their own accounts.

Getting started with the Keycloak account console

The Keycloak account console provides an interface where users can manage their own accounts, including the following:

  • Updating their user profile
  • Updating their password
  • Enabling second factor authentication
  • Viewing applications, including what applications they have authenticated to
  • Viewing open sessions, including remotely signing out of other sessions

To access the account console, open http://localhost:8080/auth/realms/myrealm/account/ in a browser (if you used a different realm name in the previous section, replace myrealm with the name of your realm). You will be redirected to the Keycloak login pages, where you can log in with the username and password you created in the previous section while creating your first user:

Figure 1.6 – The Keycloak Account Console

Figure 1.6 – The Keycloak Account Console

Tip

You can also find the URL of the account console through the Keycloak admin console. In the admin console, click on Clients, and then you will find the URL of the account console next to the account client.

You have now learned how Keycloak not only provides an extensive admin console, but also a self-management console for users of your applications to manage their own accounts.

 

Summary

In this chapter, you have learned how to install Keycloak and get it up and running. You also learned how to use the Keycloak admin console to create your first realm, including an example user with an associated role. This provides you with the foundation on which to continue building throughout the book.

In the next chapter, we will use what you have learned in this chapter in order to secure your first application with Keycloak.

 

Questions

  1. Can you run Keycloak on Docker and Kubernetes?
  2. What is the Keycloak admin Console?
  3. What is the Keycloak account console?
About the Authors
  • Stian Thorgersen

    Stian Thorgersen started his career at Arjuna Technologies building a cloud federation platform, years before most companies were even ready for a single-vendor public cloud. He later joined Red Hat, looking for ways to make developers' lives easier, which is where the idea of Keycloak started. In 2013, Stian co-founded the Keycloak project with another developer at Red Hat. Today, Stian is the Keycloak project lead and is also the top contributor to the project. He is still employed by Red Hat as a senior principal software engineer focusing on identity and access management, both for Red Hat and for Red Hat's customers. In his spare time, there is nothing Stian likes more than throwing his bike down the mountains of Norway.

    Browse publications by this author
  • Pedro Igor Silva

    Pedro Igor Silva is a proud dad of amazing girls. He started his career back in 2000 at an ISP, where he had his first experiences with open source projects such as FreeBSD and Linux, as well as a Java and J2EE software engineer. Since then, he has worked in different IT companies as a system engineer, system architect, and consultant. Today, Pedro Igor is a principal software engineer at Red Hat and one of the core developers of Keycloak. His main area of interest and study is now IT security, specifically in the application security and identity and access management spaces. In his non-working hours, he takes care of his planted aquariums.

    Browse publications by this author
Latest Reviews (3 reviews total)
Das E-Book ist günstig und die Informationen sehr hilfreich.
the book content does not cover all areas I am interested in, more insights would be great
Excellent introduction and topic explanations throughout the chapters and sample excersises.
Keycloak - Identity and Access Management for Modern Applications
Unlock this book and the full library FREE for 7 days
Start now