Keycloak - Identity and Access Management for Modern Applications - Stian Thorgersen - E-Book

Keycloak - Identity and Access Management for Modern Applications E-Book

Stian Thorgersen

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 422

Veröffentlichungsjahr: 2021

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Keycloak - Identity and Access Management for Modern Applications

Harness the power of Keycloak, OpenID Connect, and OAuth 2.0 protocols to secure applications

Stian Thorgersen

Pedro Igor Silva

BIRMINGHAM—MUMBAI

Keycloak - Identity and Access Management for Modern Applications

Copyright © 2021 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Wilson D'souza

Publishing Product Manager: Yogesh Deokar

Senior Editor: Shazeen Iqbal

Content Development Editor: Romy Dias

Technical Editor: Sarvesh Jayant

Copy Editor: Safis Editing

Project Coordinator: Shagun Saini

Proofreader: Safis Editing

Indexer: Pratik Shirodkar

Production Designer: Aparna Bhagat

First published: May 2021

Production reference: 1120521

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80056-249-3

www.packt.com

To those that are fighting against COVID-19. Specifically, to Jadiel Filho, whose memory will be forever with us.

– Pedro Igor Silva

Contributors

About the authors

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.

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.

I want to thank my wonderful family for giving me the space and support I've needed to write this book. The whole Packt editing team has helped this first-time author immensely, but I'd like to give a special thanks to Romy Dias, who edited most of my work.

About the reviewers

Hynek Mlnarik has over 20 years of experience in IT. Theoretical aspects of computer science were so attractive to him that to his own surprise, he eventually found himself holding a PhD in computer science. Yet as he likes the synergy of theory and practice, he has simultaneously worked on the architecture, development, quality engineering, and management of various IT systems, ranging from wholesale support and banking to virtualization and security. In the last few years, his main interest has been in Keycloak, which he has contributed a few lines of code to here and there, and now he reviews the lines contributed by others.

Siddhartha De holds an MS degree in systems engineering from BITS Pilani and holds around 10 years of experience in IT industries, which includes technical support, consultation, and infrastructure design. He is currently employed at Red Hat Inc. (India).

Łukasz Budnik holds a PhD in information systems and is an inside-outside technologist with over 20 years of experience designing and implementing IT solutions. He has worked on projects such as real-estate portals, car/home insurance, voice and video solutions, mobile banking, and medical systems. For the past 9 years, he has worked as a cloud architect on platforms such as AWS, Azure, Heroku, and Rackspace. Łukasz is an expert in cloud-native applications. He has been responsible for implementing rigorous security, governance, and compliance programs in the cloud.

Łukasz is a happy husband and a father to three energetic boys.

He is a huge fan of the cloud and doesn't mind the rain (at all)!

Łukasz goes by the handle @lukaszbudnik on GitHub and Twitter.

Table of Contents

Preface

Section 1: Getting Started with Keycloak

Chapter 1: Getting Started with Keycloak

Technical requirements

Introducing Keycloak

Installing and running Keycloak

Running Keycloak on Docker

Installing and running Keycloak with OpenJDK

Discovering the Keycloak admin and account consoles

Getting started with the Keycloak admin console

Getting started with the Keycloak account console

Summary

Questions

Chapter 2: Securing Your First Application

Technical requirements

Understanding the sample application

Running the application

Understanding how to log in to the application

Securely invoking the backend REST API

Summary

Questions

Section 2: Securing Applications with Keycloak

Chapter 3: Brief Introduction to Standards

Authorizing application access with OAuth 2.0

Authenticating users with OpenID Connect

Leveraging JWT for tokens

Understanding why SAML 2.0 is still relevant

Summary

Questions

Chapter 4: Authenticating Users with OpenID Connect

Technical requirements

Running the OpenID Connect playground

Understanding the Discovery endpoint

Authenticating a user

Understanding the ID token

Updating the user profile

Adding a custom property

Adding roles to the ID token

Invoking the UserInfo endpoint

Dealing with users logging out

Initiating the logout

Leveraging ID and access token expiration

Leveraging OIDC Session Management

Leveraging OIDC Back-Channel Logout

A note on OIDC Front-Channel Logout

How should you deal with logout?

Summary

Questions

Further reading

Chapter 5: Authorizing Access with OAuth 2.0

Technical requirements

Running the OAuth 2.0 playground

Obtaining an access token

Requiring user consent

Limiting the access granted to access tokens

Using the audience to limit token access

Using roles to limit token access

Using the scope to limit token access

Validating access tokens

Summary

Questions

Further reading

Chapter 6: Securing Different Application Types

Technical requirements

Understanding internal and external applications

Securing web applications

Securing server-side web applications

Securing a SPA with a dedicated REST API

Securing a SPA with an intermediary REST API

Securing a SPA with an external REST API

Securing native and mobile applications

Securing REST APIs and services

Summary

Questions

Further reading

Chapter 7: Integrating Applications with Keycloak

Technical requirements

Choosing an integration architecture

Choosing an integration option

Integrating with Golang applications

Configuring a Golang client

Integrating with Java applications

Using Quarkus

Using Spring Boot

Using Keycloak adapters

Integrating with JavaScript applications

Integrating with Node.js applications

Creating a Node.js resource server

Integrating with Python applications

Creating a Python client

Creating a Python resource server

Using a reverse proxy

Try not to implement your own integration

Summary

Questions

Further reading

Chapter 8: Authorization Strategies

Understanding authorization

Using RBAC

Using GBAC

Mapping group membership into tokens

Using OAuth2 scopes

Using ABAC

Using Keycloak as a centralized authorization server

Summary

Questions

Further reading

Section 3: Configuring and Managing Keycloak

Chapter 9: Configuring Keycloak for Production

Technical requirements

Setting the hostname for Keycloak

Setting the frontend URL

Setting the backend URL

Setting the admin URL

Enabling TLS

Configuring a database

Enabling clustering

Configuring a reverse proxy

Distributing the load across nodes

Forwarding client information

Keeping session affinity

Testing your environment

Testing load balancing and failover

Testing the frontend and backchannel URLs

Summary

Questions

Further reading

Chapter 10: Managing Users

Technical requirements

Managing local users

Creating a local user

Managing user credentials

Obtaining and validating user information

Enabling self-registration

Managing user attributes

Integrating with LDAP and Active Directory

Understanding LDAP mappers

Synchronizing groups

Synchronizing roles

Integrating with third-party identity providers

Creating a OpenID Connect identity provider

Integrating with social identity providers

Allowing users to manage their data

Summary

Questions

Further reading

Chapter 11: Authenticating Users

Technical requirements

Understanding authentication flows

Configuring an authentication flow

Using passwords

Changing password policies

Resetting user passwords

Using OTPs

Changing OTP policies

Allowing users to choose whether they want to use OTP

Forcing users to authenticate using OTP

Using Web Authentication (WebAuthn)

Enabling WebAuthn for an authentication flow

Registering a security device and authenticating

Using strong authentication

Summary

Questions

Further reading

Chapter 12: Managing Tokens and Sessions

Technical requirements

Managing sessions

Managing session lifetimes

Managing active sessions

Expiring user sessions prematurely

Understanding cookies and their relation to sessions

Managing tokens

Managing ID tokens' and access tokens' lifetimes

Managing refresh tokens' lifetimes

Enabling refreshing token rotation

Revoking tokens

Summary

Questions

Further reading

Chapter 13: Extending Keycloak

Technical requirements

Understanding Service Provider Interfaces

Packaging a custom provider

Installing a custom provider

Understanding the KeycloakSessionFactory and KeycloakSession components

Understanding the life cycle of a provider

Configuring providers

Changing the look and feel

Understanding themes

Creating and deploying a new theme

Extending templates

Extending theme-related SPIs

Customizing authentication flows

Looking at other customization points

Summary

Questions

Further reading

Section 4: Security Considerations

Chapter 14: Securing Keycloak and Applications

Securing Keycloak

Encrypting communication to Keycloak

Configuring the Keycloak hostname

Rotating the signing keys used by Keycloak

Regularly updating Keycloak

Loading secrets into Keycloak from an external vault

Protecting Keycloak with a firewall and an intrusion prevention system

Securing the database

Protecting the database with a firewall

Enabling authentication and access control for the database

Encrypting the database

Securing cluster communication

Enabling cluster authentication

Encrypting cluster communication

Securing user accounts

Securing applications

Web application security

OAuth 2.0 and OpenID Connect best practice

Keycloak client configurations

Summary

Questions

Further reading

Assessments

Other Books You May Enjoy

Preface

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.

This book introduces you to Keycloak, covering how to install Keycloak as well as how to configure it ready for production use cases. Furthermore, this book covers how to secure your own applications, as well as providing a good foundation for understanding OAuth 2.0 and OpenID Connect.

Who this book is for

This book is for developers, system administrators, and security engineers, or anyone who wants to leverage Keycloak and its capabilities to secure applications.

If you are new to Keycloak, this book will provide you with a strong foundation to leverage Keycloak in your projects.

If you have been using Keycloak for a while, but have not mastered everything yet, you should still find a lot of useful information in this book.

What this book covers

Chapter 1, Getting Started with Keycloak, gives you a brief introduction to Keycloak and steps on how to get quickly up to speed by installing and running Keycloak yourself. It also provides an introduction to the Keycloak admin and account consoles.

Chapter 2, Securing Your First Application, explains how to secure your first application with Keycloak through a sample application consisting of a single-page application and a REST API.

Chapter 3, Brief Introduction to Standards, provides a brief introduction and comparison of the standards Keycloak supports to enable you to integrate your applications securely and easily with Keycloak.

Chapter 4, Authenticating Users with OpenID Connect, teaches how to authenticate users by leveraging the OpenID Connect standard. This chapter leverages a sample application that allows you to see and understand how an application authenticates to Keycloak through Open ID Connect.

Chapter 5, Authorizing Access with OAuth 2.0, teaches how to authorize access to REST APIs and other services by leveraging the OAuth 2.0 standard. Through a sample application, you will see firsthand how an application obtains an access token through OAuth 2.0, which the application uses to invoke a protected REST API.

Chapter 6, Securing Different Application Types, covers best practices on how to secure different types of applications, including web, mobile, and native applications, as well as REST APIs and other backend services.

Chapter 7, Integrating Applications with Keycloak, provides steps on how to integrate your applications with Keycloak, covering a range of different programming languages, including Go, Java, client-side JavaScript, Node.js, and Python. It also covers how you can utilize a reverse proxy to secure an application implemented in any programming language or framework.

Chapter 8, Authorization Strategies, covers how your application can use information about the user from Keycloak for access management, covering roles and groups, as well as custom information about users.

Chapter 9, Configuring Keycloak for Production, teaches how to configure Keycloak for production, including how to enable TLS, configuring a relational database, and enabling clustering for additional scale and availability.

Chapter 10, Managing Users, takes a closer look at the capabilities provided by Keycloak related to user management. It also explains how to federate users from external sources such as LDAP, social networks, and external identity providers.

Chapter 11, Authenticating Users, covers the various authentication capabilities provided by Keycloak, including how to enable second-factor authentication, as well as security keys.

Chapter 12, Managing Tokens and Sessions, helps understand how Keycloak leverages server-side sessions to keep track of authenticated users, as well as best practices on managing tokens issued to your applications.

Chapter 13, Extending Keycloak, explains how you can extend Keycloak, covering how you can modify the look and feel of user-facing pages such as the login pages and account console. It also provides a brief introduction to one of the more powerful capabilities of Keycloak that allows you to provide custom extensions for a large number of extension points.

Chapter 14, Securing Keycloak and Applications, provides best practices on how to secure Keycloak for production. It also provides a brief introduction to some best practices to follow when securing your own applications.

To get the most out of this book

To be able to run the examples provided in this book, you need to have OpenJDK and Node.js installed on your computer. All code examples have been tested using OpenJDK 11 and Node.js 14 on Linux (Fedora). However, the examples should also work on newer versions of OpenJDK and Node.js, as well as with Windows and mac OS.

If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Keycloak-Identity-and-Access-Management-for-Modern-Applications. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Code in Action

Code in Action videos for this book can be viewed at https://bit.ly/3h6kdDm.

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/9781800562493_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Keycloak supports the authorization_code grant type and the code and token response types."

A block of code is set as follows:

<Header>.<Payload>.<Signature>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

{

  "access_token": "eyJhbGciOiJSUzI1NiIsI…",

  "expires_in": 299,

  "token_type": "bearer",

  "scope": "profile email",

  …

}

Any command-line input or output is written as follows:

$ npm install

$ npm start

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Now click on Load OpenID Provider Configuration."

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Section 1: Getting Started with Keycloak

In this section, you will get up and running with Keycloak, including securing your first application in little to no time.

This section comprises the following chapters:

Chapter 1, Getting Started with KeycloakChapter 2, Securing Your First Application

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 KeycloakInstalling and running KeycloakDiscovering 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 DockerInstalling and running Keycloak locally (which will require a Java virtual machine, such as OpenJDK)Running Keycloak on KubernetesUsing 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

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:

Windows: https://www.google.com/search?q=install+openjdk+windowsmacOS: https://www.google.com/search?q=install+openjdk+macosUbuntu: https://www.google.com/search?q=install+openjdk+ubuntu

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

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

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

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:

From the left-hand menu, click on Users, and then click on Add User.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.

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.Remember to click on Save after you have completed the 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 profileUpdating their passwordEnabling second factor authenticationViewing applications, including what applications they have authenticated toViewing 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

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

Can you run Keycloak on Docker and Kubernetes?What is the Keycloak admin Console?What is the Keycloak account console?

Chapter 2: Securing Your First Application

In this chapter, you will learn how to secure your first application with Keycloak. To make things a bit more interesting, the sample application you will be running consists of two parts, a frontend web application and a backend REST API. This will show you how a user can authenticate to the frontend, and also how the frontend is able to securely invoke the backend.

By the end of this chapter, you will have a basic understanding of how applications can be secured by Keycloak by leveraging OpenID Connect.

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

Understanding the sample applicationRunning the applicationUnderstanding how to log in to the applicationSecurely invoking the backend REST API

Technical requirements

To run the sample application included in this chapter, you need to have Node.js (https://nodejs.org/) installed on your workstation.

You also need to have a local copy of the GitHub repository associated with the book. If you have Git installed, you can clone the repository by running this command in a terminal:

$ git clone https://github.com/PacktPublishing/Keycloak-Identity-and-Access-Management-for-Modern-Applications.git

Alternatively, you can download a ZIP of the repository from

https://github.com/PacktPublishing/Keycloak-Identity-and-Access-Management-for-Modern-Applications/archive/master.zip.

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

https://bit.ly/3nQjU0W

Understanding the sample application

The sample application consists of two parts – a frontend web application and a backend REST API.

The frontend web application is a single-page application written in JavaScript. As we want to focus on what Keycloak can offer, the application is very simple. Furthermore, to make it as simple as possible to run the application, it uses Node.js. The application provides the following features:

Login with Keycloak.It displays the user's name.It displays the user's profile picture, if available.It shows the ID token.It shows the Access token.It refreshes the tokens.It invokes the secured endpoint provided by the backend.

The backend REST API is also very simple, and is implemented with Node.js. It provides a REST API with two endpoints:

/public: A publicly available endpoint with no security/secured: A secured endpoint requiring an access token with the myrealm global role

Node.js is used for the example applications as we want to make the code as easy to understand and simple to run as possible, regardless of what programming language you are familiar with.

The following diagram shows the relationship between the frontend, the backend, and Keycloak. The frontend authenticates the users using Keycloak, and then invokes the backend, which uses Keycloak to verify that the request should be permitted:

Figure 2.1 – Application overview

Now that you have a basic understanding of the sample application, let's look at some more details on how it all comes together.

When the user clicks on the login button in the frontend application, the browser is redirected to the Keycloak login page. The user then authenticates with Keycloak, before the browser is redirected back to the application with a special code called an authorization code. The application then invokes Keycloak to exchange the authorization code for the following tokens:

An ID token: This provides the application information pertaining to the authenticated user.An access token: The application includes this token when making a request to a service, which allows the service to verify whether the request should be permitted.A refresh token: Both the ID and the access token have short expirations, by default, 5 minutes. The refresh token is used by the application to obtain new tokens from Keycloak.

The flow described is what is known as the authorization code flow in OpenID Connect. If you are not already familiar with OAuth 2.0 or OpenID Connect, they can be a bit daunting at first, but once you become familiar with them, they are actually quite simple and easy to understand.

Luckily, the example application uses the Keycloak JavaScript and Node.js libraries, which means you don't actually have to understand these specifications to get started using Keycloak.

To help visualize the login process, a simplified sequence diagram is provided as follows:

Figure 2.2 – Authorization code flow in OpenID Connect simplified

The steps in this diagram are as follows:

The user clicks on the login button.The application redirects to the Keycloak login page.The Keycloak login page is displayed to the user.The user fills in the username and password and submits the results to Keycloak.After verifying the username and password, Keycloak sends the authorization code to the application.The application exchanges the authorization code for an ID token and an access token. The application can now verify the identity of the user by inspecting the ID token.

Tip

By delegating authentication of the user to Keycloak, the application does not have to know how to authenticate the user. This is especially relevant when the authentication mechanisms change. For example, two-factor authentication can be enabled without having to make changes to the application. This also means the application does not have access to the user's credentials.

The next step related to Keycloak is when the frontend invokes the backend. The backend REST API has a protected endpoint that can only be invoked by a user with the global role, myrole.

To be completely accurate, the frontend is granted permissions to invoke the backend on behalf of the user. This is part of the beauty of OAuth 2.0. An application does not have access to do everything that the user is able to do, only what it should be able to do.

When the frontend makes a request to the backend, it includes the access token within the request. By default, Keycloak uses JSON Web Signature (JWS) as the token format. These types of tokens are often referred to as non-opaque tokens, meaning the contents of the token are directly visible to the application.

The token also includes a digital signature, making it possible to verify that the token was indeed issued by Keycloak. In essence, this means that the backend can both verify the token and read the contents without a request to Keycloak, resulting in less demand on the Keycloak server and lower latency when processing requests to the backend.

To help visualize what happens when the frontend sends a request to the backend, take a look at the following diagram:

Figure 2.3 – Secured request from the frontend to the backend simplified

The steps in the diagram are as follows:

The backend retrieves Keycloak's public keys. The backend does not need to do this for all requests to the backend, but can instead cache the keys in memory.The frontend sends a request to the backend, including the access token.The backend uses the public keys it retrieved earlier to verify that the access token was issued by a trusted Keycloak instance, and then verifies that the token is valid and that the token contains the role, myrole.The backend returns the results to the frontend.

You now have a basic understanding of how the sample applications is secured with Keycloak. In the next section, you will learn how to run the sample application.

Running the application

In this section, you will learn how to run the sample application.

If you don't already have Node.js installed on your workstation, go to https://nodejs.org/ for instructions on how to install it.

To run the frontend on Node.js, open a terminal and run the following commands:

$ cd Keycloak-Identity-and-Access-Management-for-Modern-Applications/ch2/frontend/

$ npm install

$ npm start

Next, open a new terminal to run the backend using the following commands:

$ cd Keycloak-Identity-and-Access-Management-for-Modern-Applications/ch2/backend/

$ npm install

$ npm start

Now that you have the sample application running with Node.js, you can register it with Keycloak, which we will cover in the next section.

Understanding how to log in to the application

In the previous chapter, covering how to get started with Keycloak, you learned how to run Keycloak, as well as how to create your first realm. Prior to continuing this section, you should have Keycloak running with the realm created as covered in the previous chapter. In summary, what you require before continuing is the following:

Keycloak up and runningA realm named myrealmA global role named myroleA user with the preceding role

Before an application can log in with Keycloak, it has to be registered as a client with Keycloak.

Before registering the frontend, let's see what happens if an unregistered application tries to authenticate with Keycloak. Open http://localhost:8000 and then click on the Login button.

You will see an error page from Keycloak with the message Client not found. This error is telling you that the application is not registered with Keycloak.

To register the frontend with Keycloak, open the Keycloak admin console. At the top of the menu on the left-hand side, there is an option to select what realm you are working with. Make sure you have selected the realm named myrealm. In the menu on the left-hand side, click on Clients, and then click on Create.

Fill in the form with the following values:

Client ID: myclientClient Protocol: openid-connectRoot URL: http://localhost:8000

The following diagram shows the Add Client form with the values you need to fill in:

Figure 2.4 – Creating the client in the admin console

Once you have filled in the form, click on Save. After you click Save, you will see the full configuration for the client. There are two configuration options that are particularly interesting at this point:

Valid Redirect URIs: This value is very important in an OpenID Connect authorization code flow when a client-side application is used. A client-side application is not able to have any credentials as these would be visible to end users of the application. To prevent any malicious applications from being able to masquerade as the real application, the valid redirect URIs instruct Keycloak to only redirect the user to a URL that matches a valid redirect URI. In this case, since the value is set to http://localhost:8000/*, an application hosted on http://attacker.com would not be able to authenticate.Web Origins: This option registers the valid web origins for the application for Cross-Origin Resource Sharing (CORS) requests. To obtain tokens from Keycloak, the frontend application has to send an AJAX request to Keycloak, and browsers do not permit an AJAX request from one web origin to another, unless CORS is used

Now you can go back to the frontend by opening http://localhost:8000. This time, when you click on the Login button, you will see the Keycloak login page. Log in with the username and password you created during the previous chapter.

Let's take a look at the ID token that Keycloak issued. Click on the Show ID Token button. The ID token that is displayed will look something like the following:

{

  "exp": 1603912252,

  "iat": 1603911952,

  "auth_time": 1603911952,

  "jti": "363b94b8-7e0c-4852-8287-d331c98153f2",

  "iss": "http://localhost:8080/auth/realms/myrealm",

  "aud": "myclient",

  "sub": "67855660-fd6e-4416-96d1-72c99db5e525",

  "typ": "ID",

  "azp": "myclient",

  "nonce": "b59c4dbf-d196-4af7-9451-8020b153caff",

  "session_state": "32e2501f-f5ca-4d73-9fad-067d4c52835a",

  "at_hash": "7p1VYLHv2T5qRAf2X9UzSw",

  "acr": "1",

  "email_verified": false,

  "realm_access": {

    "roles": [

      "offline_access",

      "uma_authorization",

      "myrole"

    ]

  },

  "name": "Stian Thorgersen",

  "preferred_username": "st",

  "locale": "en",

  "given_name": "Stian",

  "family_name": "Thorgersen",

  "email": "st@localhost"

}

Here is a list of some of the more interesting values within the ID token:

exp: This is the date and time the token expires in seconds since 01/01/1970 00:00:00 UTC (often referred to as Unix or Epoch time).iss: This is the issuer of the token, which you may notice is the URL of the Keycloak realm.sub: This is the unique identifier of the authenticated user.name: This is the first name and last name of the authenticated user.preferred_username: This is the username of the authenticated user. You should avoid this as a key for the user as it may be changed, and even refer to a different user in the future. Instead, always use the sub field for the user key.

The ID token is used by the application to establish the identity of the authenticated user.

Next, let's take a look at the access token. Click on the Show Access Token button. Let's also take a look at some fields in this token:

allowed-origins: This is a list of permitted web origins for the application. The backend service can use this field when deciding whether web origins should be permitted for CORS requests.realm_access: This contains a list of global roles. It is the intersection between the roles granted to the user, and the roles the client has access to.resource_access: This contains a list of client roles.scope: Scopes can be used both to decide what fields (or claims) to include in the token, as well as be used by backends to decide what APIs the token can access.

Currently, the information within the tokens are the default fields available in Keycloak. If you want to add additional information, Keycloak is very flexible in allowing you to customize the contents within the tokens.

Let's give this a go by adding a picture for the user. Leave the tab with the frontend open, and then open a new tab with the Keycloak admin console. In the menu on the left-hand side, click on Users, then click on View all users, and select the user you created previously. Now let's add a custom attribute to the user. Click on Attributes