Installing Keycloak

If you’ve opted to use Keycloak as your identity provider for Keyfactor Command, you’ll need to install and configure it before installing Keyfactor Command. Keycloak can be installed in a number of ways. The following instructions cover installing it in a Docker container on a Linux machine and configuring it to use a Microsoft SQL database to store its data (configuration, user and group accounts, etc).

Tip:  Case matters for many of the values in many of the steps of the installation process. It is recommended that lower case is applied consistently in all instances when determining value names.
Important:  Keyfactor highly recommends that you use strong passwords for any accounts or certificates related to Keyfactor Command and associated products, especially when these have elevated or administrative access. A strong password has at least 12 characters (more is better) and multiple character classes (lowercase letters, uppercase letters, numeral, and symbols). Ideally, each password would be randomly generated. Avoid password re-use.
System Requirements

Keycloak has the following requirements:

  • Linux

  • Docker

  • Java version 12 or later

  • Microsoft SQL Server

This guide assumes you are starting from a base of already having a Linux server with Docker installed. Instructions for installing and configuring Linux and Docker are beyond the scope of this guide. Some helpful web pages include:

Preparing

To get ready to install Keycloak you will need to gather a few pieces of information, copy some certificate files to your Linux machine, and set up a database and user in SQL.

Installing Using Docker Compose

The following section covers installing Keycloak using a Docker compose file.

To install Keycloak in a Linux container and start the container using Docker compose:

  1. Create a directory from which you will run the Docker container. For example:

    sudo mkdir /opt/keycloak
  2. Copy the sql-truststore Java truststore you created (see Prepare Certificates) into the directory you created for the Docker container and set the permissions appropriately. It needs to be readable by the user the Docker container will run as (by default root) and its group. For example:

    sudo chown root:root sql-truststore
    sudo chmod 440 sql-truststore
  3. Copy the certificate and key for the Docker host (see Prepare Certificates) into the directory you created for the Docker container and set the permissions appropriately. They need to be readable by the user the Docker container will run as (by default root) and its group. For example:

    sudo chown root:root mycert.cer
    sudo chown root:root mycert-key-plain.pem
    sudo chmod 440 mycert.cer
    sudo chmod 440 mycert-key-plain.pem
  4. From your Docker host, retrieve the Keycloak image from the artifactory with commands similar to the following:

    sudo docker pull quay.io/keycloak/keycloak
  5. Create a Docker compose file (compose.yaml) in the directory you created for the Docker container similar to the following, using inputs as per Table 105: Keycloak Container Parameters and referencing the artifactory you pulled The fields highlighted in red below indicate fields that need to be edited or that you may wish to edit.

    Important:  When editing the file, be sure to preserve the indenting exactly as shown. YAML requires a very specific file layout to function. If the indenting (multiples of two spaces) or layout is incorrect, you will receive an error when trying to install.
    services:
      auth:
        image: quay.io/keycloak/keycloak:latest # Reference the correct artifactory
        container_name: keycloak # Give your container a name, if desired
        ports:
          - "1443:8443" # The first number is the port you will use to access Keycloak; do not change the second number
        environment:
          KC_HTTPS_CERTIFICATE_FILE: /etc/x509/https/tls.crt
          KC_HTTPS_CERTIFICATE_KEY_FILE: /etc/x509/https/tls.key
    
          KEYCLOAK_ADMIN: admin # The initial administrator user
          KEYCLOAK_ADMIN_PASSWORD: 'MySuperSecureAdminPassword' # The admin user's password needs quotes under some circumstances if it contains special characters
          CLIENT_SECRET: 'MySuperSecureKeycloakOIDCClientPassword' # FIPS compliant password used to assign a unique and complex secret for the Command-OIDC-Client
          
          KC_HOSTNAME: appsrvr18.keyexample.com # The FQDN of your Docker host
    
          # This field is only required if you're using a port other than 443
          KC_HOSTNAME_PORT: 1443
    
          # This user must be dbo on KC_DB_URL_DATABASE
          KC_DB_USERNAME: keycloak # The SQL username
          KC_DB_PASSWORD: 'MySuperSecureSQLUserPassword' # The SQL user's password needs quotes under some circumstances if it contains special characters
          KC_DB_URL_HOST: sqlsrvr05.keyexample.com # The FQDN of your SQL server
          KC_DB_URL_DATABASE: Keycloak # The database name created in SQL for Keycloak
          KC_DB: mssql
          KC_TRANSACTION_XA_ENABLED: false
          # The SQL connection string in the following value contains the truststore name and password
          KC_DB_URL_PROPERTIES: ';encrypt=true;trustServerCertificate=false;sendStringParametersAsUnicode=false;Integrated Security=False;Persist Security Info=True;trustStore=/temp/sql-truststore;trustStorePassword=MySuperSecureJKSStorePassword;'
         
          # This value must be configured even if you do not have a reverse proxy
          KC_PROXY: none
    
        command:
          - start
          - --import-realm
    
        # The first value in each of the following represents a location on your physical server, which is being mapped to a path in the container represented by the second value.
        volumes:
          - ./mycert.cer:/etc/x509/https/tls.crt
          - ./mycert-key-plain.pem:/etc/x509/https/tls.key
          - ./sql-truststore:/temp/sql-truststore
    
        # Optionally set the DNS server(s) for the Keycloak server
        dns:
          - 192.168.12.2
          - 192.168.12.3
        restart: always
  6. Set the permissions on the compose.yaml file such that the file is owned by root and readable only by root (this assumes your Docker daemon is running as root, which is typical). For example:

    sudo chown root:root compose.yaml
    sudo chmod 400 compose.yaml
    Tip:  If you need to make edits to the compose file, you will need to make the file writable again. For example:
    sudo chmod 600 compose.yaml
  7. Execute the following command to install and run the container in the foreground:

    sudo docker compose up

    You can instead run it in the background by adding the -d flag like so, but it can sometimes be helpful to run it in the foreground initially so that you can easily review the log output live:

    sudo docker compose up -d
    Tip:  To stop and start the container again after installation is complete, use the following commands:
    sudo docker compose stop
    sudo docker compose start

    Or:

    sudo docker compose restart

    If you need to delete the container and try the install again, use this command:

    sudo docker compose down

    This will not remove the configurations made in the SQL database.

    To review logs generated from the container, identify the container ID or name with this command:

    sudo docker container ls

    Or for a more succinct output:

    Copy
    sudo echo "CONTAINER ID  NAMES       STATUS" && docker container ls --format "{{.ID}}  {{.Names}}  {{.Status}}"

    For example, in the following output (this is the succinct version) you could select either the container ID 50ae6ed3decf or the name keycloak:

    CONTAINER ID  NAMES       STATUS
    daa0b06986c3  ejbca900  Up 4 weeks
    9136a6765450  ejbca900-database  Up 4 weeks
    7cf64de25b4d  ejbca920  Up 4 weeks
    4451b1ef5089  ejbca920-database  Up 4 weeks
    94a373b2f49a  rabbit-mq  Up 4 weeks
    50ae6ed3decfkeycloak  Up 4 weeks

    Then use the following command to output the current log (with the optional --follow to make output continuous):

    sudo docker container logs [--follow] [container ID or name]

Table 105: Keycloak Container Parameters

Section

Parameter

Description

image   Required*. The path to the artifactory and image for the Keycloak implementation.
container_name   A name to give to the container, if desired, for ease of reference.
environment CLIENT_SECRET Required*. Assign a complex and unique FIPS compliant secret to the Command-OIDC-Client created for Keycloak. This is provided at database initialization and is also entered in Keyfactor Command to create a connection to Keycloak, so be sure to retain this secret is a secure location.
environment KC_HTTPS_CERTIFICATE_FILE Required. The path and filename of the location within the container where the SSL certificate for the Docker host (see Prepare Certificates) will live.
environment KC_HTTPS_CERTIFICATE_KEY_FILE Required. The path and filename of the location within the container where the SSL certificate key for the Docker host (see Prepare Certificates) will live.
environment KEYCLOAK_ADMIN

Required. The username for the initial administrative user for Keycloak. The default is admin.

environment KEYCLOAK_ADMIN_PASSWORD

Required*. Set a secure password for the initial administrative user for Keycloak.

environment KC_HOSTNAME

Required*. The is the fully qualified domain name of the Docker host where you are deploying your container.

environment KC_HOSTNAME_PORT

The port number you will use to access Keycloak via a browser. This field only needs to be populated if you won’t be using 443. If you’ll be using 443, the entry should be commented out or removed.

environment KC_DB Required*. The type of SQL server. Only Microsoft SQL Server is supported (mssql).
environment KC_DB_URL_HOST Required*. The fully qualified domain name of the Microsoft SQL server that will host the database for Keycloak.
environment KC_DB_URL_DATABASE Required*. The name of the Keycloak database you pre-created in SQL per SQL Setup.
environment KC_DB_PASSWORD

Required*. The password for the SQL login to which you granted database ownership permissions on the Keycloak database per SQL Setup.

environment KC_DB_USERNAME

Required*. The username for the SQL login to which you granted database ownership permissions on the Keycloak database per SQL Setup.

environment KC_DB_URL_PROPERTIES

Required*. The SQL database connection string including the password you set to secure the Java keystore that holds the SQL server’s certificate as per Prepare Certificates.

environment KC_TRANSACTION_XA_ENABLED

A Boolean that indicates whether the database for the installation supports XA transactions.

environment KC_PROXY The proxy address forwarding mode if the server is behind a reverse proxy.
ports   The first number in the ports field indicates the port number you will use to access Keycloak via a browser and that Keyfactor Command will use to access Keycloak. If there are no other containers using this port on this Docker host, you may use 443. If 443 is already in use, you will need to change this to an alternate port (e.g. 1443). The second number in the ports field indicates the port number the Docker container uses internally. Do not change this number.
command   The command to start the container and import the realm JSON.
volumes   In this section you set the file names for the certificate and key files you copied into the directory for your Docker container. The volumes section sets mappings between files that exist on the host and locations in the running container. The first value represents a path and filename that exists on your Docker server. The second value represents a path and filename that will be created in the container containing the same information from the file referenced by the first value.
dns   In this section, add at least one IP for a DNS server that can be used to resolve hostname information for your SQL server from the Keycloak container if the SQL server’s address is not externally routable and you are not referencing the SQL server by IP address.
Configuring Keycloak and Collecting Data for the Keyfactor Command Installation

Once the Keycloak completes successfully, you should be able to open the administration console for it in a browser and gather the information you will need to complete the Keyfactor Command installation referencing it.

  1. Use a browser to open the Keycloak management interface. For example:

    https://appsrvr18.keyexample.com:1443

    Click the Administration Console link and sign in with the initial administrative user and password you defined with the KEYCLOAK_ADMIN and KEYCLOAK_ADMIN_PASSWORD settings.

    Note:  Keyfactor Command communicates with Keycloak over HTTPS, so be sure that you are working with Keycloak over HTTPS to confirm that it is working correctly with no certificate errors.
  2. In the Keycloak Administration Console, browse to Manage Realms and create a Keyfactor realm.

    Figure 510: Create a Realm in the Keycloak Administration Console for Keyfactor Data

  3. In the Keycloak Administration Console, make sure the Keyfactor realm is the current realm and browse to Clients > Client list. Create a new client for use with Keyfactor Command.

    • General Settings: Give the client a Client ID, Name and Description.

    • Capability Config: Enable Client authentication and check the Standard flow and Service accounts roles boxes.

    • Login Settings: Populate the Valid redirect URIs and Valid post logout redirect URIs fields. The values for these fields are made up of the fully qualified domain name or alias you will use to access your Keyfactor Command server, the virtual directory name you will use to access the Keyfactor CommandManagement Portal (KeyfactorPortal by default), a specific endpointClosed An endpoint is a URL that enables the API to gain access to resources on a server. for the URI, and the name you will give to Keycloak when configuring Keyfactor Command (see Authentication Tab). For example:

      • Valid redirect URIs:

        https://command.keyexample.com/KeyfactorPortal/callback/Command-OIDC
      • Valid post logout redirect URIs:

        https://command.keyexample.com/KeyfactorPortal/signout-callback/Command-OIDC
      Important:  Case matters for the virtual directory name—use KeyfactorPortal rather than keyfactorportal if you plan to accept the default virtual directory name.

      Figure 511: Create Command-OIDC-Client in the Keycloak Administration Console

  4. In the Client details on the Credentials tab click the Copy button next to the Client secret field to copy the unmasked version of the client secret to the clipboard (you do not need to display it unmasked first) and save this in a secure location. You will need it during the Keyfactor Command configuration.

    Figure 512: Copy the Keycloak Secret for the Keyfactor Command Client Application

  5. In the Keycloak Administration Console, browse to Realm settings and select the General tab. On the General tab, click the OpenID Endpoint Configuration link. This will open in a new browser window.

    Figure 513: OpenID Endpoint Configuration Link

  6. In the browser window for the OpenID Endpoint Configuration link, review the settings. You may find it helpful to use a JSON formatting browser extension to make the data easier to read. The data you need from this configuration info is:

    • Issuer (a.k.a. Authority)

    • Authorization Endpoint

    • Token Endpoint

    • User Info Endpoint

    • jwks_uri (a.k.a. JSONWebKeySetUri)

    Make note of these URLs, without the quotation marks. You will need them during the Keyfactor Command configuration.

    Figure 514: OpenID Endpoint Configuration Settings

  7. In the Keycloak Administration Console, browse to Realm settings and select the Sessions tab.

    On the Sessions tab, locate the SSO Session Max value. This value should match the Session Expiration parameterClosed A parameter or argument is a value that is passed into a function in an application. value configured in the Keyfactor Command configuration wizard on the Authentication tab. The Session Expiration value determines the length of time a Keyfactor Command browser session in the Management Portal will remain logged in before the user is prompted to re-authenticate regardless of whether the session is idle or in active use.

    Locate the SSO Session Idle value and set it to a value that is appropriate to your environment. This value determines the length of time an idle browser session in the Keyfactor Command Management Portal will remain logged in before automatically logging out the user if no input from the user is received.

    Figure 515: SSO Session Values

  8. In the Keycloak Administration Console, browse to Realm settings and select the Tokens tab. On the Tokens tab, locate the Access Token Lifespan value. This value should be greater than or equal to the Cookie Expiration parameter value configured in the Keyfactor Command configuration wizard on the Authentication tab

    The Cookie Expiration value determines the length of time the authentication cookie for the Keyfactor Command Management Portal browser session is considered valid. After half of the setting's duration, Keyfactor Command will attempt to use a refresh token to update the cookie. If this fails, the user's session will be terminated. The cookie renewal is seamless from the user’s perspective (there is no prompt for credentials).

    Figure 516: Access Token Lifespan

  9. In the Keycloak Administration Console, browse to Users. Click Create new user to add at least one new user to be granted administrative permissions in Keyfactor Command during the Keyfactor Command installation.

    Note:  The admin user(s) created during or after the Keycloak installation for ongoing management of Keycloak can’t be used for Keyfactor Command authentication because these are in the master realm, not the Keyfactor realm.
    Tip:  Once the Keyfactor Command installation is complete, additional users and groups that you have added into Keycloak can be added through the Keyfactor Command Management Portal and granted varying roles; only one user is required initially so a user can open the Management Portal at the conclusion of the installation.

    Figure 517: Add a Keycloak User

  10. Once the user account creation is complete, on the user details locate the ID for the user and make a copy of the GUID. This GUID is used to reference the user account when you configure the user as an administrator in the Keyfactor Command configuration wizard.

    Figure 518: Locate the Keycloak User’s ID

  11. In the user details on the Credentials tab, click Set password and set a password for the new user.

    Figure 519: Set a Password for the Keycloak User

From here you can create more administrative users, standard users, and groups (see Using Keycloak).