On vous demande de monter Keycloak comme IAM d’entreprise. Vous lancez kc.sh start-dev, vous vous connectez en admin/admin, vous créez un realm, vous branchez OIDC sur la première application, vous remettez ça à l’équipe d’exploitation. Six mois plus tard, le serveur tourne encore en mode dev, le realm master est toujours en admin/admin, l’instance PostgreSQL écoute sur 0.0.0.0:5432, l’issuer URL est http://localhost:8080/realms/corp dans chaque relying party parce que hostname-url n’a jamais été configuré, et l’IAM sur lequel tous les autres services s’appuient est la VM la plus faible du parc.
Ce qui se passe
Un déploiement Keycloak réellement prêt pour la production demande beaucoup plus que kc.sh start-dev. Le serveur doit tourner en mode production (kc.sh start --optimized), derrière nginx qui termine TLS avec un vrai certificat Let’s Encrypt, avec hostname configuré sur l’URL HTTPS publique pour que l’issuer OIDC inscrit dans chaque jeton corresponde à ce que les relying parties vérifient. PostgreSQL doit être lié à 127.0.0.1 uniquement. Le realm master doit être durci — mot de passe admin rouluté, compte admin par défaut remplacé par un opérateur nommé avec MFA. proxy-headers=xforwarded et nginx doivent s’accorder sur le sens de X-Forwarded-Proto, sinon Keycloak émet des URLs d’issuer avec le mauvais schéma. SSH doit avoir l’authentification par mot de passe désactivée tout en gardant l’accès clé root. Aucune de ces étapes n’est individuellement critique — sautez-les et l’IAM auquel tous les autres services font confiance devient le trou le plus facile du réseau.
Comment vérifier
Après installation, les écouteurs sur l’hôte doivent ressembler à ça :
ss -lntp | grep -E ':(80|443|8080|5432)\b'
# 127.0.0.1:5432 postgres
# 127.0.0.1:8080 keycloak
# 0.0.0.0:80 nginx
# 0.0.0.0:443 nginx
PostgreSQL sur 5432 doit être en 127.0.0.1, jamais 0.0.0.0. L’endpoint de découverte OIDC du realm master doit retourner un JSON avec l’issuer HTTPS public :
curl -fsS https://iam.example.com/realms/master/.well-known/openid-configuration | jq .issuer
# "https://iam.example.com/realms/master"
Si issuer renvoie http://localhost:8080/... ou http://iam.example.com/..., le câblage de hostname ou X-Forwarded-Proto est cassé — chaque relying party va rejeter les jetons.
Le correctif
Enregistrez le script ci-dessous sous /root/setup-keycloak-almalinux9.sh, puis exécutez-le. Il déroule l’installation sur une VM AlmaLinux 9.x fraîche : mise à jour de base + EPEL, ajustement noyau, limites de fichiers, firewalld limité à SSH + HTTP + HTTPS, durcissement SSH, dnf-automatic.timer, Temurin OpenJDK 21, PostgreSQL 15 lié à localhost, le tarball officiel de Keycloak dans /opt/keycloak, un compte de service kc-user, un keycloak.conf qui inclut proxy-headers=xforwarded et hostname, un serveur optimisé bâti (kc.sh build), une unité systemd avec LimitNOFILE=64000, nginx avec les bons entêtes forwarded, Let’s Encrypt via le plugin nginx de certbot, et une boucle d’attente qui vérifie :8080 puis :443 avant de déclarer succès.
#!/usr/bin/env bash
set -euo pipefail
### AlmaLinux 9.x Keycloak clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs and configures PostgreSQL + Keycloak + nginx + Let's Encrypt
### No local backups; assumes VM-level backup
### Reboot remains manual
if [[ "$(id -u)" -ne 0 ]]; then
echo "Run as root."
exit 1
fi
: "${KC_DOMAIN:?Set KC_DOMAIN=iam.example.com}"
: "${KC_EMAIL:?Set KC_EMAIL=ops@example.com for Let's Encrypt}"
KC_VERSION="${KC_VERSION:-26.0.5}"
KC_DB_PASSWORD="${KC_DB_PASSWORD:-$(openssl rand -hex 24)}"
KC_BOOTSTRAP_ADMIN_PASSWORD="${KC_BOOTSTRAP_ADMIN_PASSWORD:-$(openssl rand -hex 16)}"
echo
echo "========================================"
echo "Keycloak AlmaLinux 9.x Setup"
echo "========================================"
echo
echo "==> Updating base OS"
dnf -y update
dnf -y install epel-release
dnf -y update
echo "==> Installing base packages"
dnf -y install \
vim curl wget ca-certificates gnupg2 \
chrony fail2ban dnf-automatic \
policycoreutils-python-utils lsof tcpdump \
bind-utils tar gzip unzip iproute net-tools \
jq openssl
echo "==> Enabling time sync"
systemctl enable --now chronyd
timedatectl set-ntp true
echo "==> Configuring SELinux to enforcing"
if [[ -f /etc/selinux/config ]]; then
sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
fi
setenforce 1 || true
echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-keycloak.conf <<'SYSCTL'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.ip_local_port_range = 10240 65535
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
SYSCTL
modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system
echo "==> Setting file limits"
cat > /etc/security/limits.d/99-keycloak.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
LIMITS
echo "==> Configuring firewalld"
dnf -y install firewalld
systemctl enable --now firewalld
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
echo "==> Hardening SSH while keeping root SSH key login enabled"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)
set_sshd_option() {
local key="$1"
local value="$2"
if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
else
echo "${key} ${value}" >> /etc/ssh/sshd_config
fi
}
set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option KbdInteractiveAuthentication no
set_sshd_option ChallengeResponseAuthentication no
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4
sshd -t
systemctl restart sshd
echo "==> Configuring fail2ban"
mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban
echo "==> Configuring automatic security updates"
cat > /etc/dnf/automatic.conf <<'DNFAUTO'
[commands]
upgrade_type = security
random_sleep = 900
network_online_timeout = 60
download_updates = yes
apply_updates = yes
[emitters]
emit_via = stdio
[base]
debuglevel = 1
DNFAUTO
systemctl enable --now dnf-automatic.timer
echo "==> Installing Temurin OpenJDK 21"
cat > /etc/yum.repos.d/adoptium.repo <<'ADOPTIUM'
[Adoptium]
name=Adoptium
baseurl=https://packages.adoptium.net/artifactory/rpm/rhel/$releasever/$basearch
enabled=1
gpgcheck=1
gpgkey=https://packages.adoptium.net/artifactory/api/gpg/key/public
ADOPTIUM
dnf -y install temurin-21-jdk
echo "==> Installing PostgreSQL 15"
dnf -qy module disable postgresql || true
dnf -y install https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm
dnf -y install postgresql15-server postgresql15
/usr/pgsql-15/bin/postgresql-15-setup initdb || true
echo "==> Locking PostgreSQL to localhost"
PG_DATA="/var/lib/pgsql/15/data"
PG_CONF="${PG_DATA}/postgresql.conf"
sed -i "s|^#*listen_addresses.*|listen_addresses = 'localhost'|" "$PG_CONF"
systemctl enable --now postgresql-15
systemctl restart postgresql-15
echo "==> Creating Keycloak database and role"
sudo -u postgres psql <<SQL
DO \$\$
BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'kc_user') THEN
CREATE ROLE kc_user LOGIN PASSWORD '${KC_DB_PASSWORD}';
ELSE
ALTER ROLE kc_user WITH PASSWORD '${KC_DB_PASSWORD}';
END IF;
END
\$\$;
SQL
sudo -u postgres psql -tc "SELECT 1 FROM pg_database WHERE datname='keycloak'" | grep -q 1 \
|| sudo -u postgres createdb -O kc_user keycloak
echo "==> Creating kc-user service account"
if ! id -u kc-user >/dev/null 2>&1; then
useradd --system --home-dir /opt/keycloak --shell /sbin/nologin kc-user
fi
echo "==> Installing Keycloak ${KC_VERSION}"
cd /opt
if [[ ! -d "/opt/keycloak-${KC_VERSION}" ]]; then
wget -q "https://github.com/keycloak/keycloak/releases/download/${KC_VERSION}/keycloak-${KC_VERSION}.tar.gz"
tar -xf "keycloak-${KC_VERSION}.tar.gz"
rm -f "keycloak-${KC_VERSION}.tar.gz"
fi
ln -sfn "/opt/keycloak-${KC_VERSION}" /opt/keycloak
echo "==> Writing Keycloak configuration"
cat > /opt/keycloak/conf/keycloak.conf <<KCCONF
db=postgres
db-username=kc_user
db-password=${KC_DB_PASSWORD}
db-url=jdbc:postgresql://127.0.0.1:5432/keycloak
db-pool-initial-size=5
db-pool-min-size=5
db-pool-max-size=20
http-enabled=true
http-host=127.0.0.1
http-port=8080
proxy-headers=xforwarded
hostname=https://${KC_DOMAIN}
hostname-strict=true
log=console,file
log-file=/var/log/keycloak/keycloak.log
log-level=info
KCCONF
mkdir -p /var/log/keycloak
chown -R kc-user:kc-user /opt/keycloak /opt/keycloak-${KC_VERSION} /var/log/keycloak
echo "==> Building optimized server"
sudo -u kc-user /opt/keycloak/bin/kc.sh build
echo "==> Writing systemd unit"
cat > /etc/systemd/system/keycloak.service <<'UNIT'
[Unit]
Description=Keycloak
After=network.target postgresql-15.service
Requires=postgresql-15.service
[Service]
Type=simple
User=kc-user
Group=kc-user
Environment=KC_BOOTSTRAP_ADMIN_USERNAME=admin
EnvironmentFile=/etc/keycloak/admin.env
ExecStart=/opt/keycloak/bin/kc.sh start --optimized
WorkingDirectory=/opt/keycloak
LimitNOFILE=64000
Restart=on-failure
RestartSec=10
SuccessExitStatus=0 143
[Install]
WantedBy=multi-user.target
UNIT
mkdir -p /etc/keycloak
cat > /etc/keycloak/admin.env <<ADMINENV
KC_BOOTSTRAP_ADMIN_PASSWORD=${KC_BOOTSTRAP_ADMIN_PASSWORD}
ADMINENV
chmod 600 /etc/keycloak/admin.env
chown root:root /etc/keycloak/admin.env
systemctl daemon-reload
systemctl enable --now keycloak
echo "==> Waiting for Keycloak on 127.0.0.1:8080"
for i in {1..120}; do
if ss -lntp | grep -q '127.0.0.1:8080'; then
break
fi
sleep 2
done
if ! ss -lntp | grep -q '127.0.0.1:8080'; then
echo "Keycloak failed to listen on 127.0.0.1:8080"
journalctl -u keycloak -n 200 --no-pager || true
exit 1
fi
echo "==> Installing nginx and certbot"
dnf -y install nginx certbot python3-certbot-nginx
cat > /etc/nginx/conf.d/keycloak.conf <<NGINX
upstream keycloak_backend {
server 127.0.0.1:8080;
keepalive 32;
}
server {
listen 80;
listen [::]:80;
server_name ${KC_DOMAIN};
return 301 https://\$host\$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name ${KC_DOMAIN};
client_max_body_size 20M;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options nosniff always;
add_header X-Frame-Options SAMEORIGIN always;
add_header Referrer-Policy strict-origin-when-cross-origin always;
location / {
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-Host \$host;
proxy_set_header X-Forwarded-Port 443;
proxy_http_version 1.1;
proxy_pass http://keycloak_backend;
}
}
NGINX
rm -f /etc/nginx/conf.d/default.conf
nginx -t
systemctl enable --now nginx
systemctl reload nginx
echo "==> Requesting Let's Encrypt certificate"
certbot --nginx --non-interactive --agree-tos \
-m "${KC_EMAIL}" -d "${KC_DOMAIN}" --redirect
systemctl enable --now certbot.timer
echo "==> Waiting for HTTPS listener"
for i in {1..30}; do
if ss -lntp | grep -q ':443'; then
break
fi
sleep 1
done
echo "==> Final package update"
dnf -y update
echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Kernel:"
uname -r
echo
echo "SELinux:"
getenforce || true
echo
echo "SSH effective settings:"
sshd -T | grep -E '^(permitrootlogin|passwordauthentication|pubkeyauthentication) ' || true
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|5432|8080)\b' || true
echo
echo "Services:"
systemctl is-active postgresql-15 keycloak nginx fail2ban chronyd || true
echo
echo "OIDC discovery (must return JSON with the HTTPS issuer):"
curl -fsS "https://${KC_DOMAIN}/realms/master/.well-known/openid-configuration" | jq -r .issuer || true
echo
echo "Bootstrap admin: admin / ${KC_BOOTSTRAP_ADMIN_PASSWORD}"
echo "DB password: ${KC_DB_PASSWORD}"
echo "(Both written above. Record them in your secrets manager now.)"
echo
echo "Web UI:"
echo "https://${KC_DOMAIN}/admin/"
echo
echo "Final step:"
echo "Sign in as admin, create a named operator account in the master realm, grant it realm-admin, sign out, sign back in as the named account, then disable the bootstrap admin user."
Rendez-le exécutable et lancez-le :
chmod 700 /root/setup-keycloak-almalinux9.sh
KC_DOMAIN=iam.example.com KC_EMAIL=ops@example.com /root/setup-keycloak-almalinux9.sh
Le mot de passe admin de bascule est affiché à la fin — enregistrez-le dans votre gestionnaire de secrets, puis connectez-vous sur https://iam.example.com/admin/, créez un administrateur humain nommé dans le realm master, attribuez-lui realm-admin, reconnectez-vous comme ce compte, et désactivez l’utilisateur admin de bascule. Activez l’OTP comme action requise sur le realm master. Les sauvegardes au niveau hôte ne sont pas configurées ici ; un pg_dump de la base keycloak doit être couvert par votre politique de snapshots VM.
Quand le comportement de l’IAM doit rester stable à travers les changements de realm, les mises à jour de thème et les sorties trimestrielles de Keycloak, ça relève de la Supervision et support sur appel — ou réservez une revue d’infrastructure rapide.