#!/bin/bash # Variables KC_HOST="http://localhost:8080" REALM="master" CLIENT_ID="soa" CLIENT_SECRET="mysecret" USERNAME="alexis" PASSWORD="password" PERSONAL_TOKEN="personaltoken" # Fonction d'attente wait_for_keycloak() { echo "⏳ Attente de Keycloak..." until curl -s "$KC_HOST" > /dev/null; do sleep 2 done echo "✅ Keycloak est prêt." } # Obtenir un token admin get_admin_token() { curl -s -X POST "$KC_HOST/realms/master/protocol/openid-connect/token" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "username=admin" \ -d "password=admin" \ -d "grant_type=password" \ -d "client_id=admin-cli" | jq -r .access_token } # Générer une date d'expiration (1 an à partir de maintenant) generate_expiry_date() { date -d "+1 year" --iso-8601=seconds } # Créer un realm, client et utilisateur setup_keycloak() { TOKEN=$(get_admin_token) CURRENT_DATE=$(date --iso-8601=seconds) EXPIRY_DATE=$(generate_expiry_date) echo "🛠️ Création du realm $REALM..." curl -s -X POST "$KC_HOST/admin/realms" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d "{\"realm\":\"$REALM\",\"enabled\":true}" > /dev/null echo "🛠️ Création du client $CLIENT_ID..." curl -s -X POST "$KC_HOST/admin/realms/$REALM/clients" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d "{ \"clientId\": \"$CLIENT_ID\", \"enabled\": true, \"publicClient\": false, \"secret\": \"$CLIENT_SECRET\", \"redirectUris\": [\"*\"], \"standardFlowEnabled\": true, \"serviceAccountsEnabled\": true, \"authorizationServicesEnabled\": false }" > /dev/null echo "👤 Création de l'utilisateur $USERNAME avec token personnel..." curl -s -X POST "$KC_HOST/admin/realms/$REALM/users" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d "{ \"username\": \"$USERNAME\", \"enabled\": true, \"emailVerified\": true, \"attributes\": { \"api_token\": [\"$PERSONAL_TOKEN\"], \"token_created\": [\"$CURRENT_DATE\"], \"token_expires\": [\"$EXPIRY_DATE\"], \"created_by\": [\"setup_script\"], \"department\": [\"IT\"], \"access_level\": [\"developer\"] }, \"credentials\": [{ \"type\": \"password\", \"value\": \"$PASSWORD\", \"temporary\": false }] }" echo "✅ Configuration terminée !" echo "🔐 Utilisateur: $USERNAME / $PASSWORD" echo "🪪 Client secret: $CLIENT_SECRET" echo "🎫 Personal Access Token: $PERSONAL_TOKEN" echo "📅 Token créé le: $CURRENT_DATE" echo "⏰ Token expire le: $EXPIRY_DATE" } # Fonction pour tester le token test_personal_token() { echo "Pour accéder à une ressource protégée:" echo "curl -X GET http://localhost:3000/api/protected" echo " -H \"Authorization: Bearer $PERSONAL_TOKEN\"" } # Lancer le setup wait_for_keycloak setup_keycloak test_personal_token