Using Keycloak as the OpenShift Admin Login Page

Organizations usually want all their applications to use a centralized login page (SSO), including platforms such as OpenShift. That’s why, in this tutorial, we’ll set up a simple login page for our OpenShift Container Platform (OCP) using Keycloak.

First, let’s deploy a Keycloak instance along with a PostgreSQL database.

apiVersion: v1
kind: Service
metadata:
  name: keycloak
  labels:
    app: keycloak
spec:
  ports:
    - protocol: TCP
      port: 8080
      targetPort: http
      name: http
  selector:
    app: keycloak
  type: ClusterIP
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: keycloak
  name: keycloak-discovery
spec:
  selector:
    app: keycloak
  clusterIP: None
  type: ClusterIP
---
apiVersion: apps/v1
# Use a StatefulSet to ensure that Pods are restarted one at a time during rolling updates.
# This helps prevent the loss of in-memory information stored redundantly across two Pods.
kind: StatefulSet
metadata:
  name: keycloak
  labels:
    app: keycloak
spec:
  serviceName: keycloak-discovery
  # Use one replica to save resources, or two replicas to allow rolling updates for configuration changes.
  replicas: 2
  selector:
    matchLabels:
      app: keycloak
  template:
    metadata:
      labels:
        app: keycloak
    spec:
      containers:
        - name: keycloak
          image: quay.io/keycloak/keycloak:26.8.2
          args: ["start"]
          env:
            - name: KC_BOOTSTRAP_ADMIN_USERNAME
              value: "admin"
            - name: KC_BOOTSTRAP_ADMIN_PASSWORD
              value: "admin"
            # In a production environment, configure a TLS certificate for Keycloak to encrypt traffic
            # either between the client and Keycloak or between your reverse proxy and Keycloak.
            # Configure Keycloak to respect the proxy headers forwarded by the reverse proxy.
            # If you continue to use proxy headers, verify your proxy configuration and restrict
            # access to Keycloak so that only trusted proxies can connect to it.
            - name: KC_PROXY_HEADERS
              value: "xforwarded"
            - name: KC_HTTP_ENABLED
              value: "true"
            # For this exploratory setup, no strict hostname is configured.
            # In production, configure a hostname for a more secure setup.
            - name: KC_HOSTNAME_STRICT
              value: "false"
            - name: KC_HEALTH_ENABLED
              value: "true"
            - name: 'KC_CACHE'
              value: 'ispn'
            # Pass the Pod's IP address to JGroups, as this is required in IPv6-only setups.
            - name: POD_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            # Tell JGroups which IP address to use when discovering other Keycloak nodes.
            # This configuration must be unique for each Keycloak cluster.
            - name: KC_CACHE_EMBEDDED_NETWORK_BIND_ADDRESS
              value: '$(POD_IP)'
            - name: 'KC_DB_URL_DATABASE'
              value: 'keycloak'
            - name: 'KC_DB_URL_HOST'
              value: 'postgres'
            - name: 'KC_DB'
              value: 'postgres'
            # In production, use a Secret to store the database username and password.
            - name: 'KC_DB_PASSWORD'
              value: 'keycloak'
            - name: 'KC_DB_USERNAME'
              value: 'keycloak'
          ports:
            - name: http
              containerPort: 8080
            - name: jgroups
              containerPort: 7800
            - name: jgroups-fd
              containerPort: 57800
          startupProbe:
            httpGet:
              path: /health/started
              port: 9000
            periodSeconds: 1
            failureThreshold: 600
          readinessProbe:
            httpGet:
              path: /health/ready
              port: 9000
            periodSeconds: 10
            failureThreshold: 3
          livenessProbe:
            httpGet:
              path: /health/live
              port: 9000
            periodSeconds: 10
            failureThreshold: 3
          resources:
            limits:
              cpu: 2000m
              memory: 2000Mi
            requests:
              cpu: 500m
              memory: 1700Mi
---
# This PostgreSQL deployment uses ephemeral storage for testing.
# Once the Pod stops, all database data is lost.
# For production, replace this with a database setup that provides persistent storage.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
  labels:
    app: postgres
spec:
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
        - name: postgres
          image: mirror.gcr.io/postgres:17
          env:
            - name: POSTGRES_USER
              value: "keycloak"
            - name: POSTGRES_PASSWORD
              value: "keycloak"
            - name: POSTGRES_DB
              value: "keycloak"
            - name: POSTGRES_LOG_STATEMENT
              value: "all"
          ports:
            - name: postgres
              containerPort: 5432
          volumeMounts:
            # Mount PostgreSQL's data directory to make it writable.
            - name: postgres-data
              mountPath: /var/lib/postgresql/data
      volumes:
        - name: postgres-data
          emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: postgres
  name: postgres
spec:
  selector:
    app: postgres
  ports:
    - protocol: TCP
      port: 5432
      targetPort: 5432
  type: ClusterIP

Log in to Keycloak using the admin/admin credentials, and create a new realm. Let’s name it apps.

After that, create a new client with the following configuration:

– Client ID: openshift
– Valid redirect URIs: https://oauth-openshift.apps-crc.testing/*
– Client authentication: On
– Authentication flow: Standard flow

Create the client and save its client secret. We’ll need it later when configuring OpenShift.

## Configure OpenShift to use Keycloak

Next, we’ll configure OpenShift to use Keycloak as its login provider. First, we need to store the Keycloak client secret in an OpenShift Secret.

$ oc create secret generic keycloak-client-secret -n openshift-config 
        --from-literal=clientSecret=aAqyccF8LuXV1GIvbvswLIbCwQWi0k6vk9ul0uPJvkxonjDrWeBrGKfVT9b4Axxxxx
secret/keycloak-client-secret created

Next, we need to register Keycloak’s SSL certificate with OpenShift. In this example, Keycloak is deployed on OpenShift, so it uses the same certificate as the other routes.

$ oc get configmap default-ingress-cert -n openshift-config-managed 
        -o jsonpath='{.data.ca-bundle\.crt}' > ca.crt

$ oc create configmap keycloak-ca -n openshift-config 
        --from-file=ca.crt=ca.crt
configmap/keycloak-ca created

Now, let’s update the OpenShift OAuth configuration to add Keycloak as an identity provider.

apiVersion: config.openshift.io/v1
kind: OAuth
metadata:
  annotations:
    include.release.openshift.io/ibm-cloud-managed: "true"
    include.release.openshift.io/self-managed-high-availability: "true"
    release.openshift.io/create-only: "true"
  name: cluster
spec:
  identityProviders:
  - htpasswd:
      fileData:
        name: htpass-secret
    mappingMethod: claim
    name: developer
    type: HTPasswd
  - mappingMethod: claim
    name: keycloak
    openID:
      ca:
        name: keycloak-ca
      claims:
        email:
        - email
        name:
        - name
        preferredUsername:
        - preferred_username
      clientID: openshift
      clientSecret:
        name: keycloak-client-secret
      extraScopes:
      - email
      - profile
      issuer: https://keycloak-sso.apps-crc.testing/realms/apps
    type: OpenID

Apply the configuration:

$ oc apply -f oauth-cluster.yaml
oauth.config.openshift.io/cluster configured

Wait a few moments for the configuration to take effect. You should now see that the OpenShift login page has changed.

Try logging in using your Keycloak credentials. Once authenticated, we can use the following command to verify that the Keycloak user has been imported into OpenShift.

$ oc get users
NAME            UID                                    FULL NAME       IDENTITIES
admin-console   dbfa1c8a-98e0-4d03-b92c-b93fc825d69c   admin console   keycloak:37319975-c5fc-43b6-a029-46587d0e3ff7
kubeadmin       b3fbdbf1-bfd1-4efa-8404-f4d4edbcf43a                   developer:kubeadmin

Finally, let’s grant the admin-console user the admin role in the sample-namespace namespace.

$ oc adm policy add-role-to-user admin admin-console -n sample-namespace
clusterrole.rbac.authorization.k8s.io/admin added: "admin-console"

Leave a Comment

Your email address will not be published.